package com.hskn.hss.module.cases.service.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hskn.hss.app.unread.vo.NewsCountVo;
import com.hskn.hss.constant.CommonConstant;
import com.hskn.hss.core.annotation.DataScope;
import com.hskn.hss.core.domain.BaseEntity;
import com.hskn.hss.core.page.TableDataInfo;
import com.hskn.hss.core.utils.LoginUtils;
import com.hskn.hss.exception.HssException;
import com.hskn.hss.module.caseprocess.entity.CaseProcess;
import com.hskn.hss.module.caseprocess.entity.CaseProcessFull;
import com.hskn.hss.module.caseprocess.mapper.CaseProcessMapper;
import com.hskn.hss.module.caseprocess.service.ICaseProcessService;
import com.hskn.hss.module.cases.entity.Cases;
import com.hskn.hss.module.cases.entity.CasesCharts2;
import com.hskn.hss.module.cases.entity.CasesFull;
import com.hskn.hss.module.cases.entity.CasesTable;
import com.hskn.hss.module.cases.mapper.CasesMapper;
import com.hskn.hss.module.cases.service.ICasesService;
import com.hskn.hss.module.cases.to.EventDistributionTO;
import com.hskn.hss.module.cases.vo.*;
import com.hskn.hss.module.casesetissue.entity.CasesetIssue;
import com.hskn.hss.module.casesetissue.mapper.CasesetIssueMapper;
import com.hskn.hss.module.casesetissue.service.ICasesetIssueService;
import com.hskn.hss.module.casesetlevel.entity.CasesetLevel;
import com.hskn.hss.module.casesetlevel.service.ICasesetLevelService;
import com.hskn.hss.module.casesetsys.entity.CasesetSys;
import com.hskn.hss.module.casesetsys.service.ICasesetSysService;
import com.hskn.hss.module.depart.entity.SysDepart;
import com.hskn.hss.module.depart.mapper.SysDepartMapper;
import com.hskn.hss.module.depart.service.ISysDepartService;
import com.hskn.hss.module.messageFlowRecords.domain.MessageFlowRecords;
import com.hskn.hss.module.messageFlowRecords.service.IMessageFlowRecordsService;
import com.hskn.hss.module.role.entity.SysRole;
import com.hskn.hss.module.role.mapper.SysRoleMapper;
import com.hskn.hss.module.tlemployee.entity.TIEmployeeVo;
import com.hskn.hss.module.tlemployee.entity.TlEmployee;
import com.hskn.hss.module.tlemployee.mapper.TlEmployeeMapper;
import com.hskn.hss.module.tlemployee.service.ITlEmployeeService;
import com.hskn.hss.module.user.entity.User;
import com.hskn.hss.module.user.mapper.UserMapper;
import com.hskn.hss.module.user.service.IUserService;
import com.hskn.hss.module.userdepart.entity.SysUserDepart;
import com.hskn.hss.module.userdepart.mapper.SysUserDepartMapper;
import com.hskn.hss.module.userdepart.service.ISysUserDepartService;
import com.hskn.hss.module.userrole.entity.SysUserRole;
import com.hskn.hss.module.userrole.mapper.SysUserRoleMapper;
import com.hskn.hss.utils.*;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.toList;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author hskn
 * @since 2021-05-18
 */
@Service
public class CasesServiceImpl extends ServiceImpl<CasesMapper, Cases> implements ICasesService {

    @Autowired
    public IMessageFlowRecordsService messageFlowRecordsService;
    @Resource
    SysUserDepartMapper sysUserDepartMapper;
    @Autowired
    ICasesetLevelService casesetLevelService;
    @Autowired
    ISysUserDepartService sysUserDepartService;
    @Autowired
    IUserService userService;
    @Autowired
    ICasesetIssueService casesetIssueService;
    @Autowired
    ICasesetSysService iCasesetSysService;
    @Resource
    TlEmployeeMapper tlEmployeeMapper;
    @Resource
    UserMapper userMapper;
    @Autowired
    UpdateCache updateCache;
    @Autowired
    LocationUtils locationUtil;
    @Resource
    private CasesMapper casesMapper;
    @Resource
    private CaseProcessMapper caseProcessMapper;
    @Autowired
    private ICaseProcessService caseProcessService;
    @Resource
    private SysDepartMapper sysDepartMapper;
    @Autowired
    private ISysDepartService departService;
    @Autowired
    private ISysUserDepartService userDepartService;
    @Resource
    private SysUserRoleMapper sysUserRoleMapper;
    @Resource
    private SysRoleMapper sysRoleMapper;

    @Override
    @DataScope(deptAlias = "depid", userAlias = "create_uid,person_id,cc_uid")
    public JSONObject mList(BaseEntity entity, JSONObject params) throws HssException {

        String uid = LoginUtils.getUser().getUid();
        JSONObject json = new JSONObject();
        if (params == null) {
            params = new JSONObject();
        }
        QueryWrapper<Cases> queryWrapper = new QueryWrapper<>();
        String sortType = params.getString("sortType");
        String sortField = params.getString("sortField");
        if (entity.getParams().containsKey("dataScope")&&StringUtils.isNotEmpty(entity.getParams().get("dataScope"))) {
            queryWrapper.lambda().apply(entity.getParams().get("dataScope").toString());
        }
        if (StringUtils.isNotEmpty(sortField) && StringUtils.isNotEmpty(sortType) && "asc".equals(sortType)) {
            queryWrapper.lambda().orderByAsc(Cases::getCreateTime);
        } else {
            queryWrapper.lambda().orderByDesc(Cases::getCreateTime);
        }
        String caseId = params.getString("caseId");
        if (StringUtils.isNotEmpty(caseId)) {
            queryWrapper.lambda().eq(Cases::getCaseId, caseId);
        }
        String ids = params.getString("ids");
        if (StringUtils.isNotEmpty(ids)) {
            queryWrapper.lambda().in(Cases::getCaseId, Arrays.asList(ids.split(",")));
        }
        String personId = params.getString("personId");
        if (StringUtils.isNotEmpty(personId)) {
            queryWrapper.lambda().eq(Cases::getPersonId, personId);
        }
        Integer status = params.getInteger("status");
        if (StringUtils.isNotEmpty(status)) {
            List<String> strings = Arrays.asList(String.valueOf(status).split(","));
            queryWrapper.lambda().in(Cases::getStatus, strings);
        }
        String statuses = params.getString("statuses");
        if (StringUtils.isNotEmpty(statuses)) {
            queryWrapper.lambda().in(Cases::getStatus, statuses.split(","));
        }
        String depId = params.getString("depId");
        if (StringUtils.isNotEmpty(depId)) {
            queryWrapper.lambda().eq(Cases::getDepid, depId);
        }
        String caseIssueId = params.getString("caseIssueId");
        if (StringUtils.isNotEmpty(caseIssueId)) {
            queryWrapper.lambda().eq(Cases::getCaseIssueId, caseIssueId);
        }
        String caseIssueChildId = params.getString("caseIssueChildId");
        if (StringUtils.isNotEmpty(caseIssueChildId)) {
            queryWrapper.lambda().eq(Cases::getCaseIssueChildId, caseIssueChildId);
        }
        String caseNo = params.getString("caseNo");
        if (StringUtils.isNotEmpty(caseNo)) {
            queryWrapper.lambda().like(Cases::getCaseNo, caseNo);
        }
        String caseLevelId = params.getString("caseLevelId");
        if (StringUtils.isNotEmpty(caseLevelId)) {
            queryWrapper.lambda().eq(Cases::getCaseLevelId, caseLevelId);
        }
        String startDate = AttributeUtils.timeCompletion(params.getString("startDate"), 's');
        String endDate = AttributeUtils.timeCompletion(params.getString("endDate"), 'e');
        String date = params.getString("date");
        if (StringUtils.isNotEmpty(startDate) && StringUtils.isNotEmpty(endDate)) {
            queryWrapper.lambda().between(Cases::getCreateTime, startDate, endDate);
        } else if (StringUtils.isNotEmpty(date) && StringUtils.isNotEmpty(date)) {
            queryWrapper.lambda().between(Cases::getCreateTime, date + " 00:00:00.0", date + " 23:59:59.999");
        }
        String isPostpone = params.getString("isPostpone");
        if (StringUtils.isNotEmpty(isPostpone)) {
            queryWrapper.lambda().eq(Cases::getIsPostpone, isPostpone);
        }
        String isOverdue = params.getString("isOverdue");
        if (StringUtils.isNotEmpty(isOverdue)) {
            queryWrapper.lambda().eq(Cases::getIsOverdue, isOverdue);
        }
        String createUid = params.getString("createUid");
        if (StringUtils.isNotEmpty(createUid)) {
            queryWrapper.lambda().eq(Cases::getCreateUid, createUid);
        }

        Long page = StringUtils.isEmpty(params.getLong("page")) ? 1 : params.getLong("page");
        Long size = StringUtils.isEmpty(params.getLong("size")) ? 10 : params.getLong("size");
        Page<Cases> casesPage = new Page<>(page, size, true);
        IPage<Cases> iPage = casesMapper.selectPage(casesPage, queryWrapper);

        List<CasesetLevel> casesetLevels = casesetLevelService.list();
        List<Cases> casesList = iPage.getRecords();
        List<String> arr = new ArrayList<>();
        for (Cases cases : casesList) {
            if (StringUtils.isNotEmpty(cases.getCcUid())) {
                User user = userService.getById(cases.getCcUid());
                if (StringUtils.isNotEmpty(user)) {
                    cases.setCcName(user.getName());
                }
            }
            arr.add(cases.getCaseId());
            for (CasesetLevel level : casesetLevels) {
                if (level.getCasesetLevelId().equals(cases.getCaseLevelId())) {
                    cases.setCaseLevelName(level.getName());
                    break;
                }
            }

            MessageFlowRecords messageFlowRecords = new MessageFlowRecords();
            messageFlowRecords.setMessageId(cases.getCaseId());
            messageFlowRecords.setKind(3);
            messageFlowRecords.setSubjectType(1);
            messageFlowRecords.setUserId(uid);
            List<MessageFlowRecords> messageFlowRecords1 = messageFlowRecordsService.selectMessageFlowRecordsList(messageFlowRecords);
            if (Objects.nonNull(messageFlowRecords1) && messageFlowRecords1.size() > 0) {
                cases.setIsRead(1);
            } else {
                cases.setIsRead(0);
            }
        }
        if (!arr.isEmpty()) {
            List<String> list = new ArrayList<>();
            list.add("分派");
            list.add("改派");
            QueryWrapper<CaseProcess> casesQueryWrapper = new QueryWrapper<>();
            casesQueryWrapper.in("case_id", arr);
            casesQueryWrapper.in("handle", list);
            casesQueryWrapper.last("GROUP BY case_id");
            List<CaseProcess> caseProcessList = caseProcessMapper.selectList(casesQueryWrapper);
            for (int i = 0; i < casesList.size(); i++) {
                for (int j = 0; j < caseProcessList.size(); j++) {
                    if (caseProcessList.get(j).getCaseId().equals(casesList.get(i).getCaseId())) {
                        casesList.get(i).setAppointTime(caseProcessList.get(j).getCreateTime());
                        casesList.get(i).setAppointName(caseProcessList.get(j).getCreateAccount());
                    }
                }
            }
        }
        //casesQueryWrapper.eq("status", 1);
        json.put("total", iPage.getTotal());
        json.put("size", iPage.getSize());
        json.put("pages", iPage.getPages());
        json.put("current", iPage.getCurrent());
        json.put("cases", casesList);
        return json;
    }

    @Override
    public JSONObject appmList(JSONObject params) {

        String uid = LoginUtils.getUser().getUid();
        Integer roleType = LoginUtils.getLoginUserIdentity();
        JSONObject json = new JSONObject();
        User user = userMapper.selectById(uid);
        if (Objects.isNull(user)) {
            return json;
        }

        QueryWrapper<Cases> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().orderByDesc(Cases::getCreateTime);
        if (CommonConstant.ROLE_USER == roleType){
            if ("1".equals(params.getString("type")))
            {
                queryWrapper.lambda().eq(Cases::getPersonId, uid);
            } else {
                queryWrapper.lambda().eq(Cases::getCreateUid, uid);
            }
        }
        Integer status = params.getInteger("status");
        if (StringUtils.isNotEmpty(status)) {
            queryWrapper.lambda().eq(Cases::getStatus, status);
        }
        String depId = params.getString("depId");
        if (StringUtils.isNotEmpty(depId)) {
            queryWrapper.lambda().eq(Cases::getDepid, depId);
        }
        String caseIssueId = params.getString("caseIssueId");
        if (StringUtils.isNotEmpty(caseIssueId)) {
            queryWrapper.lambda().eq(Cases::getCaseIssueId, caseIssueId);
        }
        String caseIssueChildId = params.getString("caseIssueChildId");
        if (StringUtils.isNotEmpty(caseIssueChildId)) {
            queryWrapper.lambda().eq(Cases::getCaseIssueChildId, caseIssueChildId);
        }
        String caseNo = params.getString("caseNo");
        if (StringUtils.isNotEmpty(caseNo)) {
            queryWrapper.lambda().like(Cases::getCaseNo, caseNo);
        }
        String caseLevelId = params.getString("caseLevelId");
        if (StringUtils.isNotEmpty(caseLevelId)) {
            queryWrapper.lambda().eq(Cases::getCaseLevelId, caseLevelId);
        }
        String startDate = params.getString("startDate");
        String endDate = params.getString("endDate");
        String date = params.getString("date");
        if (StringUtils.isNotEmpty(startDate) && StringUtils.isNotEmpty(endDate)) {
            queryWrapper.lambda().between(Cases::getCreateTime, startDate, endDate);
        } else if (StringUtils.isNotEmpty(date) && StringUtils.isNotEmpty(date)) {
            queryWrapper.lambda().between(Cases::getCreateTime, date + " 00:00:00", date + " 23:59:59");
        }
        String isPostpone = params.getString("isPostpone");
        if (StringUtils.isNotEmpty(isPostpone)) {
            queryWrapper.lambda().eq(Cases::getIsPostpone, isPostpone);
        }
        String isOverdue = params.getString("isOverdue");
        if (StringUtils.isNotEmpty(isOverdue)) {
            queryWrapper.lambda().eq(Cases::getIsOverdue, isOverdue);
        }
        Long page = StringUtils.isEmpty(params.getLong("page")) ? 1 : params.getLong("page");
        Long size = StringUtils.isEmpty(params.getLong("size")) ? 10 : params.getLong("size");
        Page<Cases> casesPage = new Page<>(page, size, true);
        IPage<Cases> iPage = casesMapper.selectPage(casesPage, queryWrapper);

        for (Cases cases : iPage.getRecords()) {
            QueryWrapper<CaseProcess> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.lambda().eq(CaseProcess::getCaseId, cases.getCaseId());
            queryWrapper1.lambda().eq(CaseProcess::getHandle, "签到");
            List<CaseProcess> caseProcess1 = caseProcessMapper.selectList(queryWrapper1);
            if (caseProcess1 != null && !caseProcess1.isEmpty()) {
                cases.setSign(1);
            }
        }
        json.put("total", iPage.getTotal());
        json.put("size", iPage.getSize());
        json.put("pages", iPage.getPages());
        json.put("current", iPage.getCurrent());
        json.put("cases", iPage.getRecords());
        return json;
    }

    @Override
    @DataScope(deptAlias = "depid", userAlias = "create_uid,person_id,cc_uid")
    public List<JSONObject> amount(BaseEntity entity,JSONObject params) {

        return casesMapper.amount(entity);
    }

    @Override
    @Transactional
    public void mUpdate(JSONObject params) throws HssException {

        if (StringUtils.isEmpty(params) || StringUtils.isEmpty(params.getString("caseId"))) {
            throw new HssException("参数错误");
        }
        Cases cases = JSON.parseObject(params.toJSONString(), Cases.class);

        List<CasesetIssue> casesetIssueList = casesetIssueService.list();
        if (StringUtils.isNotEmpty(cases.getCaseIssueId())) {
            for (CasesetIssue issue : casesetIssueList) {
                if (cases.getCaseIssueId().equals(issue.getCasesetIssueId())) {
                    cases.setCaseIssueName(issue.getName());
                }
            }
        }
        if (StringUtils.isNotEmpty(cases.getCaseIssueChildId())) {
            for (CasesetIssue issue : casesetIssueList) {
                if (cases.getCaseIssueChildId().equals(issue.getCasesetIssueId())) {
                    cases.setCaseIssueChildName(issue.getName());
                }
            }
        }
        casesMapper.updateById(cases);
    }

    @Override
    @Transactional
    public void add(JSONObject params) throws HssException {

        String uid = LoginUtils.getUser().getUid();
        String account = LoginUtils.getUser().getAccount();
        Cases cases = JSON.parseObject(params.toJSONString(), Cases.class);
        Map<String, User> userMap = userService.getUserMap();
        cases.setCaseId(StringUtils.uuid());
        if (StringUtils.isNotEmpty(cases.getIsPlatformAssign()) && cases.getIsPlatformAssign() == 1) {
            cases.setStatus(1);
        } else {
            cases.setStatus(2);
            cases.setConsumingTime("1秒");
            if (StringUtils.isNotEmpty(cases.getPersonId())) {
                User user = userMapper.selectById(cases.getPersonId());
                if (Objects.nonNull(user)) {
                    cases.setPersonName(user.getName());
                }
                QueryWrapper<SysUserDepart> queryWrapper = new QueryWrapper<>();
                queryWrapper.lambda().eq(SysUserDepart::getUserid, cases.getPersonId());
                SysUserDepart userDepart = sysUserDepartMapper.selectOne(queryWrapper);
                if (StringUtils.isNotEmpty(userDepart)) {
                    String deptid = userDepart.getDepid();
                    QueryWrapper<SysDepart> queryWrapper2 = new QueryWrapper<>();
                    queryWrapper2.lambda().eq(SysDepart::getId, deptid);
                    SysDepart sysDepart = sysDepartMapper.selectOne(queryWrapper2);
                    if (StringUtils.isNotEmpty(sysDepart)) {
                        String deptname = sysDepart.getDepartName();
                        cases.setDepid(deptid);
                        cases.setDepName(deptname);
                    }
                }
            }
        }

        List<CasesetIssue> casesetIssueList = casesetIssueService.list();
        if (StringUtils.isNotEmpty(cases.getCaseIssueId())) {
            for (CasesetIssue issue : casesetIssueList) {
                if (cases.getCaseIssueId().equals(issue.getCasesetIssueId())) {
                    cases.setCaseIssueName(issue.getName());
                }
            }
        }
        if (StringUtils.isNotEmpty(cases.getCaseIssueChildId())) {
            for (CasesetIssue issue : casesetIssueList) {
                if (cases.getCaseIssueChildId().equals(issue.getCasesetIssueId())) {
                    cases.setCaseIssueChildName(issue.getName());
                }
            }
        }
        if (null == cases.getCasesetIssueSourceId()) {
            cases.setCasesetIssueSourceId("3c49e738aa9624236b635a0d3b1f4344");
        }
        cases.setCreateUid(uid);
        User user = userMap.get(uid);
        if (Objects.nonNull(user)){
            cases.setCreateName(user.getName());
        } else {
            cases.setCreateName(account);
        }
        cases.setCaseNo(StringUtils.getNo());
        casesMapper.insert(cases);

        CaseProcess caseProcess = new CaseProcess();
        caseProcess.setCaseId(cases.getCaseId());
        caseProcess.setHandle("创建");
        caseProcess.setCreateUid(uid);
        caseProcess.setRemark(cases.getDes());
        caseProcess.setCreateAccount(account);
        caseProcess.setImgUrls(cases.getImgUrl());
        caseProcess.setVideoUrl(cases.getVideoUrl());
        //事件推送
        sendMessage(cases, uid, account);

        caseProcessMapper.insert(caseProcess);
    }

    public void sendMessage(Cases cases, String uid, String account) {
        if (StringUtils.isNotEmpty(cases.getPersonId())) {
            JSONObject alarmJson = new JSONObject();
            alarmJson.put("model", 5);
            JSONObject detailJson = new JSONObject();
            detailJson.put("id", cases.getCaseId());
            detailJson.put("remindKey", "eventInspectReport");
            detailJson.put("happenTime", DateUtil.formatDateTime(new Date()));
            detailJson.put("lng", cases.getLng());
            detailJson.put("lat", cases.getLat());
            detailJson.put("address", cases.getAddress());
            detailJson.put("pic", cases.getImgUrl());
            detailJson.put("typeId", cases.getCaseIssueId());
            detailJson.put("typeName", cases.getCaseIssueName());
            detailJson.put("authorId", uid);
            detailJson.put("authorName", account);
            detailJson.put("authorType", "cases");
            detailJson.put("personId", cases.getPersonId());
            detailJson.put("personName", cases.getPersonName());
            detailJson.put("status", cases.getStatus());
            alarmJson.put("detail", detailJson);
            WebSocketUtils.sendMessageToOne(alarmJson.toString(), cases.getPersonId());

            QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.lambda().notIn(User::getUid, cases.getPersonId());
            List<User> userList = userMapper.selectList(userQueryWrapper);

            QueryWrapper<SysUserRole> sysUserRoleQueryWrapper = new QueryWrapper<>();
            List<SysUserRole> sysUserRoleList = sysUserRoleMapper.selectList(sysUserRoleQueryWrapper);
            Map<String, List<SysUserRole>> sysUserRoleMap = sysUserRoleList.stream().collect(Collectors.groupingBy(SysUserRole::getUserid));

            QueryWrapper<SysRole> sysRoleQueryWrapper = new QueryWrapper<>();
            List<SysRole> sysRoleList = sysRoleMapper.selectList(sysRoleQueryWrapper);
            Map<String, SysRole> sysRoleMap = sysRoleList.stream().collect(Collectors.groupingBy(SysRole::getId, Collectors.collectingAndThen(toList(), values -> values.get(0))));

            userList.forEach(user -> {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("model", 1);
                JSONObject object = new JSONObject();
                object.put("id", cases.getCaseId());
                //公众号投诉是否选中 event_public_complaints
                //建设意见是否选中 event_construction_opinion
                //巡查上报是否选中 event_inspect_report
                //问题督办是否选中 event_problem_overseeing
                //维修上报是否选中 event_maintenance_report
                object.put("remindKey", "eventInspectReport");
                object.put("happenTime", DateUtil.formatDateTime(new Date()));
                object.put("lng", cases.getLng());
                object.put("lat", cases.getLat());
                object.put("address", cases.getAddress());
                object.put("pic", cases.getImgUrl());
                object.put("typeId", cases.getCaseIssueId());
                object.put("typeName", cases.getCaseIssueName());
                object.put("authorId", uid);
                object.put("authorName", account);
                object.put("authorType", "cases");
                object.put("personId", cases.getPersonId());
                object.put("personName", cases.getPersonName());
                object.put("status", cases.getStatus());
                jsonObject.put("detail", detailJson);
                List<SysUserRole> sysUserRoleList1 = sysUserRoleMap.get(user.getUid());
                if (null != sysUserRoleList1) {
                    for (SysUserRole sysUserRole : sysUserRoleList1) {
                        SysRole sysRole = sysRoleMap.get(sysUserRole.getRoleid());
                        if (null != sysRole) {
                            if (sysRole.getRoleName().equals("管理员")) {
                                WebSocketUtils.sendMessageToOne(jsonObject.toString(), sysUserRole.getUserid());
                            }
                        }
                    }
                }
            });
        } else {
            QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
            List<User> userList = userMapper.selectList(userQueryWrapper);

            QueryWrapper<SysUserRole> sysUserRoleQueryWrapper = new QueryWrapper<>();
            List<SysUserRole> sysUserRoleList = sysUserRoleMapper.selectList(sysUserRoleQueryWrapper);
            Map<String, List<SysUserRole>> sysUserRoleMap = sysUserRoleList.stream().collect(Collectors.groupingBy(SysUserRole::getUserid));

            QueryWrapper<SysRole> sysRoleQueryWrapper = new QueryWrapper<>();
            List<SysRole> sysRoleList = sysRoleMapper.selectList(sysRoleQueryWrapper);
            Map<String, SysRole> sysRoleMap = sysRoleList.stream().collect(Collectors.groupingBy(SysRole::getId, Collectors.collectingAndThen(toList(), values -> values.get(0))));


            User user1 = LoginUtils.getUser();
            JSONObject alarmJson1 = new JSONObject();
            alarmJson1.put("model", 1);
            JSONObject detailJson1 = new JSONObject();
            detailJson1.put("id", cases.getCaseId());
            detailJson1.put("remindKey", "eventInspectReport");
            detailJson1.put("happenTime", DateUtil.formatDateTime(new Date()));
            detailJson1.put("lng", cases.getLng());
            detailJson1.put("lat", cases.getLat());
            detailJson1.put("address", cases.getAddress());
            detailJson1.put("pic", cases.getImgUrl());
            detailJson1.put("typeId", cases.getCaseIssueId());
            detailJson1.put("typeName", cases.getCaseIssueName());
            detailJson1.put("authorId", uid);
            detailJson1.put("authorName", account);
            detailJson1.put("authorType", "cases");
            detailJson1.put("personId", cases.getPersonId());
            detailJson1.put("personName", cases.getPersonName());
            detailJson1.put("status", cases.getStatus());
            alarmJson1.put("detail", detailJson1);
            List<SysUserRole> sysUserRoleList2 = sysUserRoleMap.get(user1.getUid());
            if (null != sysUserRoleList2) {
                for (SysUserRole sysUserRole : sysUserRoleList2) {
                    SysRole sysRole = sysRoleMap.get(sysUserRole.getRoleid());
                    if (null != sysRole) {
                        if (!sysRole.getRoleName().equals("管理员")) {
                            WebSocketUtils.sendMessageToOne(alarmJson1.toString(), user1.getUid());
                        }
                    }
                }
            }
            for (User user : userList) {
                JSONObject alarmJson = new JSONObject();
                alarmJson.put("model", 1);
                JSONObject detailJson = new JSONObject();
                detailJson.put("id", cases.getCaseId());
                detailJson.put("remindKey", "eventInspectReport");
                detailJson.put("happenTime", DateUtil.formatDateTime(new Date()));
                detailJson.put("lng", cases.getLng());
                detailJson.put("lat", cases.getLat());
                detailJson.put("address", cases.getAddress());
                detailJson.put("pic", cases.getImgUrl());
                detailJson.put("typeId", cases.getCaseIssueId());
                detailJson.put("typeName", cases.getCaseIssueName());
                detailJson.put("authorId", uid);
                detailJson.put("authorName", account);
                detailJson.put("authorType", "cases");
                detailJson.put("personId", cases.getPersonId());
                detailJson.put("personName", cases.getPersonName());
                detailJson.put("status", cases.getStatus());
                alarmJson.put("detail", detailJson);
                List<SysUserRole> sysUserRoleList1 = sysUserRoleMap.get(user.getUid());
                if (null != sysUserRoleList1) {
                    for (SysUserRole sysUserRole : sysUserRoleList1) {
                        SysRole sysRole = sysRoleMap.get(sysUserRole.getRoleid());
                        if (null != sysRole) {
                            if (sysRole.getRoleName().equals("管理员")) {
                                WebSocketUtils.sendMessageToOne(alarmJson.toString(), sysUserRole.getUserid());
                            }
                        }
                    }
                }
            }
        }
    }

    @Override
    public void del(JSONObject params) throws HssException {

        if (StringUtils.isEmpty(params) || StringUtils.isEmpty(params.getString("caseIds"))) {
            throw new HssException("参数错误");
        }
        String idStr = params.getString("caseIds");
        String[] ids = idStr.split(",");
        casesMapper.deleteBatchIds(Arrays.asList(ids));
    }

    @Override
    public CasesFull detail(JSONObject params) throws HssException {

        String uid = LoginUtils.getUser().getUid();
        if (StringUtils.isEmpty(params) || StringUtils.isEmpty(params.getString("caseId"))) {
            throw new HssException("参数错误");
        }
        Cases cases = casesMapper.selectById(params.getString("caseId"));
        CasesFull casesFull = JSON.parseObject(JSONObject.toJSONString(cases), CasesFull.class);
//        QueryWrapper<CaseProcess> queryWrapper = new QueryWrapper<>();
//        queryWrapper.lambda().orderByDesc(CaseProcess::getCreateTime);
//        queryWrapper.lambda().eq(CaseProcess::getCaseId, cases.getCaseId());

        if (casesFull != null && StringUtils.isNotEmpty(casesFull.getPersonId())) {
            User u = userService.getById(casesFull.getPersonId());
            if (StringUtils.isNotEmpty(u)) {
                casesFull.setPersonName(u.getName());
            }
        }

        User user = null;
        if (casesFull != null && StringUtils.isNotEmpty(casesFull.getCcUid())) {
            user = userService.getById(casesFull.getCcUid());
            if (StringUtils.isNotEmpty(user)) {
                casesFull.setCcName(user.getName());
            }
        }

        CasesetLevel level = null;
        if (casesFull != null) {
            level = casesetLevelService.getById(casesFull.getCaseLevelId());
        }
        if (StringUtils.isNotEmpty(level)) {
            casesFull.setCaseLevelName(level.getName());
        }

        List<CaseProcessFull> caseProcessFulls = new ArrayList<>();
        if (cases != null) {
            caseProcessFulls = caseProcessMapper.selectFullListByCaseId(cases.getCaseId());
        }
        for (CaseProcessFull processFull : caseProcessFulls) {
            if (StringUtils.isNotEmpty(processFull.getHandle()) && "催办".equals(processFull.getHandle())) {
                SysDepart depart = sysUserDepartService.getDeptByUid(processFull.getCreateUid());
                if (StringUtils.isNotEmpty(depart)) {
                    processFull.setDepName(depart.getDepartName());
                }
            } else if (StringUtils.isNotEmpty(processFull.getHandle()) && ("分派".equals(processFull.getHandle()) || "改派".equals(processFull.getHandle()))) {
                if (StringUtils.isNotEmpty(user)) {
                    processFull.setCcName(user.getName());
                }
                if (StringUtils.isNotEmpty(level)) {
                    processFull.setCaseLevelName(level.getName());
                }
            }
        }
        if (casesFull != null) {
            casesFull.setCaseProcesses(caseProcessFulls);
        }

        MessageFlowRecords messageFlowRecords = new MessageFlowRecords();
        messageFlowRecords.setMessageId(casesFull.getCaseId());
        messageFlowRecords.setKind(3);
        messageFlowRecords.setSubjectType(1);
        messageFlowRecords.setUserId(uid);
        List<MessageFlowRecords> messageFlowRecords1 = messageFlowRecordsService.selectMessageFlowRecordsList(messageFlowRecords);
        if (Objects.isNull(messageFlowRecords1) || messageFlowRecords1.size() == 0) {
            messageFlowRecords.setCreateTime(new Date());
            messageFlowRecords.setId(StringUtils.uuid());
            messageFlowRecords.setSubjuctId(casesFull.getPersonId());
            User person = userMapper.selectById(casesFull.getPersonId());
            if (person != null) {
                messageFlowRecords.setSubjuctName(person.getName());
            }
            messageFlowRecords.setContent(casesFull.getDes());
            User user1 = userMapper.selectById(uid);
            if (user1 != null) {
                messageFlowRecords.setUserName(user1.getName());
            }
            messageFlowRecordsService.insertMessageFlowRecordsOnly(messageFlowRecords);
        }
        return casesFull;
    }

    @Override
    @Transactional
    public void archive(JSONObject params) throws HssException {

        String uid = LoginUtils.getUser().getUid();
        String account = LoginUtils.getUser().getAccount();
        String startDate = params.getString("startDate");
        String endDate = params.getString("endDate");
        if (StringUtils.isEmpty(startDate) || StringUtils.isEmpty(endDate)) {
            throw new HssException("缺少参数");
        }
        QueryWrapper<Cases> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().between(Cases::getCreateTime, startDate, endDate);
        queryWrapper.lambda().ne(Cases::getIsArchive, 1);
        List<Cases> cases = casesMapper.selectList(queryWrapper);
        if (StringUtils.isNotEmpty(cases)) {
            List<CaseProcess> caseProcesses = new ArrayList<>();
            for (Cases aCase : cases) {
                CaseProcess caseProcess = new CaseProcess();
                caseProcess.setCaseId(aCase.getCaseId());
                caseProcess.setHandle("归档");
                caseProcess.setCreateUid(uid);
                caseProcess.setCreateAccount(account);
                caseProcesses.add(caseProcess);
                aCase.setIsArchive(1);
            }
            caseProcessService.saveBatch(caseProcesses);
            updateBatchById(cases);
        }
    }

    @Override
    @Transactional
    public void jiean(JSONObject params) throws HssException {

        String uid = LoginUtils.getUser().getUid();
        String account = LoginUtils.getUser().getAccount();
        if (StringUtils.isEmpty(params) || StringUtils.isEmpty(params.getString("caseIds"))) {
            throw new HssException("参数错误");
        }
        String idStr = params.getString("caseIds");
        String[] ids = idStr.split(",");
        List<String> idList = Arrays.asList(ids);
        QueryWrapper<Cases> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().in(Cases::getCaseId, idList);
        List<Cases> cases = casesMapper.selectList(queryWrapper);
        if (StringUtils.isEmpty(cases)) {
            throw new HssException("无匹配数据");
        }
        List<CaseProcess> caseProcesses = new ArrayList<>();
        for (Cases aCase : cases) {
            if (1 == aCase.getIsArchive()) {
                throw new HssException("案件已归档，不能操作！");
            }
            if (5 == aCase.getStatus()) {
                throw new HssException("该案件已废弃，请恢复后再操作！");
            }
            if (4 == aCase.getStatus()) {
                throw new HssException("该案件已结案，请不要重复结案！");
            }
            CaseProcess caseProcess = new CaseProcess();
            caseProcess.setCaseId(aCase.getCaseId());
            caseProcess.setHandle("结案");
            caseProcess.setCreateUid(uid);
            caseProcess.setCreateAccount(account);
            if (params != null && params.containsKey("remark")) {
                caseProcess.setRemark(params.getString("remark"));
            }
            QueryWrapper<CaseProcess> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.lambda().eq(CaseProcess::getCaseId, aCase.getCaseId());
            queryWrapper1.lambda().orderByDesc(CaseProcess::getCreateTime);
            queryWrapper1.lambda().ne(CaseProcess::getHandle, "催办");
            queryWrapper1.lambda().last("limit 1");
            CaseProcess caseProcess1 = caseProcessMapper.selectOne(queryWrapper1);
            if (StringUtils.isNotEmpty(caseProcess1) && StringUtils.isNotEmpty(caseProcess1.getCreateTime())) {
                caseProcess.setCosttimedetail(StringUtils.subDate(caseProcess1.getCreateTime()));
            }
            caseProcesses.add(caseProcess);
            aCase.setStatus(4);
        }
        caseProcessService.saveBatch(caseProcesses);
        updateBatchById(cases);
    }

    @Override
    @Transactional
    public void cuiban(JSONObject params) throws HssException {

        String uid = LoginUtils.getUser().getUid();
        String account = LoginUtils.getUser().getAccount();
        if (StringUtils.isEmpty(params) || StringUtils.isEmpty(params.getString("caseIds"))) {
            throw new HssException("参数错误");
        }
        String remark = params.getString("remark");
        String idStr = params.getString("caseIds");
        String[] ids = idStr.split(",");
        List<String> idList = Arrays.asList(ids);
        QueryWrapper<Cases> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().in(Cases::getCaseId, idList);
        List<Cases> cases = casesMapper.selectList(queryWrapper);
        if (StringUtils.isEmpty(cases)) {
            throw new HssException("无匹配数据");
        }
        List<CaseProcess> caseProcesses = new ArrayList<>();
        for (Cases aCase : cases) {
            if (1 == aCase.getIsArchive()) {
                throw new HssException("案件已归档，不能操作！");
            }
            if (5 == aCase.getStatus()) {
                throw new HssException("该案件已废弃，请恢复后再操作！");
            }
            if (4 == aCase.getStatus()) {
                throw new HssException("该案件已结案，不能操作");
            }
            aCase.setIsUrge(1);
            CaseProcess caseProcess = new CaseProcess();
            caseProcess.setCaseId(aCase.getCaseId());
            caseProcess.setHandle("催办");
            caseProcess.setCreateUid(uid);
            caseProcess.setCreateAccount(account);
            if (StringUtils.isNotEmpty(remark)) {
                caseProcess.setRemark(remark);
            }
            QueryWrapper<CaseProcess> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.lambda().eq(CaseProcess::getCaseId, aCase.getCaseId());
            queryWrapper1.lambda().orderByDesc(CaseProcess::getCreateTime);
            queryWrapper1.lambda().ne(CaseProcess::getHandle, "催办");
            queryWrapper1.lambda().last("limit 1");
            CaseProcess caseProcess1 = caseProcessMapper.selectOne(queryWrapper1);
            if (StringUtils.isNotEmpty(caseProcess1) && StringUtils.isNotEmpty(caseProcess1.getCreateTime())) {
                caseProcess.setCosttimedetail(StringUtils.subDate(caseProcess1.getCreateTime()));
            }
            caseProcesses.add(caseProcess);
            // TODO: 2021/5/18 给app推送催办消息
        }
        updateBatchById(cases);
        caseProcessService.saveBatch(caseProcesses);
    }

    @Override
    @Transactional
    public void feiqi(JSONObject params) throws HssException {

        String uid = LoginUtils.getUser().getUid();
        String account = LoginUtils.getUser().getAccount();
        if (StringUtils.isEmpty(params) || StringUtils.isEmpty(params.getString("caseIds"))) {
            throw new HssException("参数错误");
        }
        String idStr = params.getString("caseIds");
        String[] ids = idStr.split(",");
        List<String> idList = Arrays.asList(ids);
        QueryWrapper<Cases> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().in(Cases::getCaseId, idList);
        List<Cases> cases = casesMapper.selectList(queryWrapper);
        if (StringUtils.isEmpty(cases)) {
            throw new HssException("无匹配数据");
        }
        List<CaseProcess> caseProcesses = new ArrayList<>();
        for (Cases aCase : cases) {
            if (1 == aCase.getIsArchive()) {
                throw new HssException("案件已归档，不能操作！");
            }
            if (5 == aCase.getStatus()) {
                throw new HssException("该案件已废弃，请不要重复操作！");
            }
            CaseProcess caseProcess = new CaseProcess();
            caseProcess.setCaseId(aCase.getCaseId());
            caseProcess.setHandle("废弃");
            caseProcess.setCreateUid(uid);
            caseProcess.setCreateAccount(account);
            QueryWrapper<CaseProcess> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.lambda().eq(CaseProcess::getCaseId, aCase.getCaseId());
            queryWrapper1.lambda().orderByDesc(CaseProcess::getCreateTime);
            queryWrapper1.lambda().ne(CaseProcess::getHandle, "催办");
            queryWrapper1.lambda().last("limit 1");
            CaseProcess caseProcess1 = caseProcessMapper.selectOne(queryWrapper1);
            if (StringUtils.isNotEmpty(caseProcess1) && StringUtils.isNotEmpty(caseProcess1.getCreateTime())) {
                caseProcess.setCosttimedetail(StringUtils.subDate(caseProcess1.getCreateTime()));
            }
            caseProcesses.add(caseProcess);
            aCase.setBeforeFqStatus(aCase.getStatus());
            aCase.setStatus(5);
        }
        caseProcessService.saveBatch(caseProcesses);
        updateBatchById(cases);
    }

    @Override
    @Transactional
    public void huifu(JSONObject params) throws HssException {

        String uid = LoginUtils.getUser().getUid();
        String account = LoginUtils.getUser().getAccount();

        if (StringUtils.isEmpty(params) || StringUtils.isEmpty(params.getString("caseIds"))) {
            throw new HssException("参数错误");
        }
        String idStr = params.getString("caseIds");
        String[] ids = idStr.split(",");
        List<String> idList = Arrays.asList(ids);
        QueryWrapper<Cases> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().in(Cases::getCaseId, idList);
        List<Cases> cases = casesMapper.selectList(queryWrapper);
        if (StringUtils.isEmpty(cases)) {
            throw new HssException("无匹配数据");
        }
        List<CaseProcess> caseProcesses = new ArrayList<>();
        for (Cases aCase : cases) {
            if (1 == aCase.getIsArchive()) {
                throw new HssException("案件已归档，不能操作！");
            }
            if (5 != aCase.getStatus()) {
                throw new HssException("非废弃工单不需要恢复！");
            }
            CaseProcess caseProcess = new CaseProcess();
            caseProcess.setCaseId(aCase.getCaseId());
            caseProcess.setHandle("恢复");
            caseProcess.setCreateUid(uid);
            caseProcess.setCreateAccount(account);
            caseProcesses.add(caseProcess);
            if (StringUtils.isNotEmpty(aCase.getBeforeFqStatus())) {
                aCase.setStatus(aCase.getBeforeFqStatus());
            } else if (StringUtils.isEmpty(aCase.getPersonId())) {
                aCase.setStatus(1);
            } else {
                aCase.setStatus(2);
            }
        }
        caseProcessService.saveBatch(caseProcesses);
        updateBatchById(cases);
    }

    @Override
    @Transactional
    public void gaipai(JSONObject params) throws HssException {

        String uid = LoginUtils.getUser().getUid();
        String account = LoginUtils.getUser().getAccount();
        if (StringUtils.isEmpty(params) || StringUtils.isEmpty(params.getString("caseId"))) {
            throw new HssException("参数错误");
        }
        if (StringUtils.isEmpty(params) || StringUtils.isEmpty(params.getString("personId"))) {
            throw new HssException("参数错误");
        }
        String caseId = params.getString("caseId");
        String personId = params.getString("personId");
        String personAccount = params.getString("personAccount");
        String ccUid = params.getString("ccUid");
        String remark = params.getString("remark");
        String caseLevelId = params.getString("caseLevelId");
        Integer timelimit = params.getInteger("timelimit");
        Integer isSendSms = params.getInteger("isSendSms");

        Cases cases = casesMapper.selectById(caseId);
        if (StringUtils.isEmpty(cases)) {
            throw new HssException("不存在的案件");
        }

        if (1 == cases.getIsArchive()) {
            throw new HssException("案件已归档，不能操作！");
        }
        if (5 == cases.getStatus()) {
            throw new HssException("该案件已废弃，请不要重复操作！");
        }
        if (4 == cases.getStatus()) {
            throw new HssException("该案件已结案，不能操作");
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("model", 5);
        JSONObject detailJson = new JSONObject();
        detailJson.put("id", cases.getCaseId());
        detailJson.put("remindKey", "eventInspectReport");
        detailJson.put("happenTime", DateUtil.formatDateTime(new Date()));
        detailJson.put("lng", cases.getLng());
        detailJson.put("lat", cases.getLat());
        detailJson.put("address", cases.getAddress());
        detailJson.put("pic", cases.getImgUrl());
        detailJson.put("typeId", cases.getCaseIssueId());
        detailJson.put("typeName", cases.getCaseIssueName());
        detailJson.put("authorId", uid);
        detailJson.put("authorName", account);
        detailJson.put("authorType", "cases");
        detailJson.put("personId", cases.getPersonId());
        detailJson.put("personName", cases.getPersonName());
        detailJson.put("status", cases.getStatus());
        jsonObject.put("detail", detailJson);
        WebSocketUtils.sendMessageToOne(jsonObject.toString(), cases.getPersonId());

        CaseProcess caseProcess = new CaseProcess();

        if (StringUtils.isNotEmpty(timelimit)) {
            cases.setTimelimit(timelimit);
            caseProcess.setTimelimit(timelimit);
        }

        if (StringUtils.isNotEmpty(isSendSms)) {
            caseProcess.setIsSendSms(isSendSms);
            if (1 == isSendSms) {
                // TODO: 2021/6/22 短信通知被指派人
            }
        }

        cases.setPersonId(personId);
        User user = userService.getById(personId);
        String personName = "";
        if (Objects.nonNull(user)) {
            personName = user.getName();
        }
        cases.setPersonName(personName);
        cases.setStatus(2);
        cases.setSign(0);

        QueryWrapper<SysUserDepart> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysUserDepart::getUserid, cases.getPersonId());
        SysUserDepart userDepart = sysUserDepartMapper.selectOne(queryWrapper);
        if (StringUtils.isNotEmpty(userDepart)) {
            String deptid = userDepart.getDepid();
            QueryWrapper<SysDepart> queryWrapper2 = new QueryWrapper<>();
            queryWrapper2.lambda().eq(SysDepart::getId, deptid);
            SysDepart sysDepart = sysDepartMapper.selectOne(queryWrapper2);
            if (StringUtils.isNotEmpty(sysDepart)) {
                String deptname = sysDepart.getDepartName();
                cases.setDepid(deptid);
                cases.setDepName(deptname);
            }
        }

        if (StringUtils.isNotEmpty(ccUid)) {
            cases.setCcUid(ccUid);
            caseProcess.setCcUid(ccUid);
        }
        casesMapper.updateById(cases);

        if (StringUtils.isNotEmpty(caseLevelId)) {
            caseProcess.setCaseLevelId(caseLevelId);
        }

        caseProcess.setCaseId(caseId);
        caseProcess.setHandle("改派");
        caseProcess.setCreateUid(uid);
        caseProcess.setCreateAccount(account);
        caseProcess.setPersonId(personId);
        caseProcess.setPersonAccount(personAccount);
        QueryWrapper<CaseProcess> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.lambda().eq(CaseProcess::getCaseId, caseId);
        queryWrapper1.lambda().orderByDesc(CaseProcess::getCreateTime);
        queryWrapper1.lambda().ne(CaseProcess::getHandle, "催办");
        queryWrapper1.lambda().last("limit 1");
        CaseProcess caseProcess1 = caseProcessMapper.selectOne(queryWrapper1);
        if (StringUtils.isNotEmpty(caseProcess1) && StringUtils.isNotEmpty(caseProcess1.getCreateTime())) {
            caseProcess.setCosttimedetail(StringUtils.subDate(caseProcess1.getCreateTime()));
        }
        if (StringUtils.isNotEmpty(remark)) {
            caseProcess.setRemark(remark);
        }
        caseProcessMapper.insert(caseProcess);
        // TODO: 2021/5/18 给分派人推送消息
        if (StringUtils.isNotEmpty(ccUid)) {
            // TODO: 2021/5/18 给抄送人推送消息
        }
    }

    @Override
    @Transactional
    public void chuli(JSONObject params) throws HssException {

        String uid = LoginUtils.getUser().getUid();
        String account = LoginUtils.getUser().getAccount();
        if (StringUtils.isEmpty(params) || StringUtils.isEmpty(params.getString("caseId"))) {
            throw new HssException("参数错误");
        }
        String caseId = params.getString("caseId");
        Cases cases = casesMapper.selectById(caseId);
        if (StringUtils.isEmpty(cases)) {
            throw new HssException("不存在的案件");
        }

        if (!uid.equals(cases.getPersonId())) {
            throw new HssException("请不要处理非本人工单");
        }
        if (1 == cases.getIsArchive()) {
            throw new HssException("案件已归档，不能操作！");
        }
        if (5 == cases.getStatus()) {
            throw new HssException("该案件已废弃，不能操作！");
        }
        if (4 == cases.getStatus()) {
            throw new HssException("该案件已结案，不能操作");
        }
        if (1 == cases.getStatus()) {
            throw new HssException("该案件还未分派，不能处理");
        }

        CaseProcess caseProcess = new CaseProcess();

        String imgUrlOk = params.getString("imgUrlOk");
        String videoUrlOk = params.getString("videoUrlOk");
        String voiceUrlOk = params.getString("voiceUrlOk");
        if (StringUtils.isNotEmpty(imgUrlOk)) {
            cases.setImgUrlOk(imgUrlOk);
            caseProcess.setImgUrls(imgUrlOk);
        }
        if (StringUtils.isNotEmpty(videoUrlOk)) {
            cases.setVideoUrlOk(videoUrlOk);
            caseProcess.setVideoUrl(videoUrlOk);
        }
        if (StringUtils.isNotEmpty(voiceUrlOk)) {
            cases.setVoiceUrlOk(voiceUrlOk);
        }
        cases.setStatus(3);
        casesMapper.updateById(cases);

        String remark = params.getString("remark");
        caseProcess.setCaseId(caseId);
        caseProcess.setHandle("处理");
        caseProcess.setCreateUid(uid);
        caseProcess.setCreateAccount(account);
        QueryWrapper<CaseProcess> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.lambda().eq(CaseProcess::getCaseId, caseId);
        queryWrapper1.lambda().orderByDesc(CaseProcess::getCreateTime);
        queryWrapper1.lambda().ne(CaseProcess::getHandle, "催办");
        queryWrapper1.lambda().last("limit 1");
        CaseProcess caseProcess1 = caseProcessMapper.selectOne(queryWrapper1);
        if (StringUtils.isNotEmpty(caseProcess1) && StringUtils.isNotEmpty(caseProcess1.getCreateTime())) {
            caseProcess.setCosttimedetail(StringUtils.subDate(caseProcess1.getCreateTime()));
        }
        if (StringUtils.isNotEmpty(remark)) {
            caseProcess.setRemark(remark);
        }
        caseProcessMapper.insert(caseProcess);
    }

    @Override
    @Transactional
    public void assigned(JSONObject params) throws HssException {

        String uid = LoginUtils.getUser().getUid();
        String account = LoginUtils.getUser().getAccount();
        if (StringUtils.isEmpty(params) || StringUtils.isEmpty(params.getString("caseId"))) {
            throw new HssException("参数错误");
        }
        if (StringUtils.isEmpty(params) || StringUtils.isEmpty(params.getString("personId"))) {
            throw new HssException("参数错误");
        }
        String caseId = params.getString("caseId");
        String personId = params.getString("personId");
        String personAccount = "";
        User user = userService.getById(personId);
        User user1 = userService.getById(uid);
        if (user != null) {
            personAccount = user.getName();
        }
        String ccUid = params.getString("ccUid");
        String remark = params.getString("remark");
        String caseLevelId = params.getString("caseLevelId");
        Integer timelimit = params.getInteger("timelimit");
        Integer isSendSms = params.getInteger("isSendSms");

        Cases cases = casesMapper.selectById(caseId);
        if (StringUtils.isEmpty(cases)) {
            throw new HssException("不存在的案件");
        }

        if (1 == cases.getIsArchive()) {
            throw new HssException("案件已归档，不能操作！");
        }
        if (5 == cases.getStatus()) {
            throw new HssException("该案件已废弃，不能操作！");
        }
        if (4 == cases.getStatus()) {
            throw new HssException("该案件已结案，不能操作");
        }
        if (3 == cases.getStatus()) {
            throw new HssException("该案件已处理，不能分派");
        }

        CaseProcess caseProcess = new CaseProcess();

        if (StringUtils.isNotEmpty(timelimit)) {
            cases.setTimelimit(timelimit);
            caseProcess.setTimelimit(timelimit);
        }

        if (StringUtils.isNotEmpty(isSendSms)) {
            caseProcess.setIsSendSms(isSendSms);
            if (1 == isSendSms) {
                // TODO: 2021/6/22 短信通知被指派人
            }
        }

        cases.setPersonId(personId);
        cases.setPersonName(personAccount);
        cases.setStatus(2);
        cases.setAppointTime(new Date());
        cases.setAppointName(user1.getAccount());


        QueryWrapper<SysUserDepart> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysUserDepart::getUserid, personId);
        SysUserDepart userDepart = sysUserDepartMapper.selectOne(queryWrapper);
        if (StringUtils.isNotEmpty(userDepart)) {
            String deptid = userDepart.getDepid();
            QueryWrapper<SysDepart> queryWrapper2 = new QueryWrapper<>();
            queryWrapper2.lambda().eq(SysDepart::getId, deptid);
            SysDepart sysDepart = sysDepartMapper.selectOne(queryWrapper2);
            if (StringUtils.isNotEmpty(sysDepart)) {
                String deptname = sysDepart.getDepartName();
                cases.setDepid(deptid);
                cases.setDepName(deptname);
            }
        }

        if (StringUtils.isNotEmpty(ccUid)) {
            caseProcess.setCcUid(ccUid);
            cases.setCcUid(ccUid);
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("model", 5);
        JSONObject detailJson = new JSONObject();
        detailJson.put("id", cases.getCaseId());
        detailJson.put("remindKey", "eventInspectReport");
        detailJson.put("happenTime", DateUtil.formatDateTime(new Date()));
        detailJson.put("lng", cases.getLng());
        detailJson.put("lat", cases.getLat());
        detailJson.put("address", cases.getAddress());
        detailJson.put("pic", cases.getImgUrl());
        detailJson.put("typeId", cases.getCaseIssueId());
        detailJson.put("typeName", cases.getCaseIssueName());
        detailJson.put("authorId", uid);
        detailJson.put("authorName", account);
        detailJson.put("authorType", "cases");
        detailJson.put("personId", cases.getPersonId());
        detailJson.put("personName", cases.getPersonName());
        detailJson.put("status", cases.getStatus());
        jsonObject.put("detail", detailJson);
        WebSocketUtils.sendMessageToOne(jsonObject.toString(), cases.getPersonId());
        casesMapper.updateById(cases);

        caseProcess.setCaseId(caseId);
        caseProcess.setHandle("分派");
        caseProcess.setCreateUid(uid);
        caseProcess.setCreateAccount(account);
        caseProcess.setPersonId(personId);
        caseProcess.setPersonAccount(personAccount);
        QueryWrapper<CaseProcess> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.lambda().eq(CaseProcess::getCaseId, caseId);
        queryWrapper1.lambda().orderByDesc(CaseProcess::getCreateTime);
        queryWrapper1.lambda().ne(CaseProcess::getHandle, "催办");
        queryWrapper1.lambda().last("limit 1");
        CaseProcess caseProcess1 = caseProcessMapper.selectOne(queryWrapper1);
        if (StringUtils.isNotEmpty(caseProcess1) && StringUtils.isNotEmpty(caseProcess1.getCreateTime())) {
            caseProcess.setCosttimedetail(StringUtils.subDate(caseProcess1.getCreateTime()));
        }
        if (StringUtils.isNotEmpty(remark)) {
            caseProcess.setRemark(remark);
        }
        caseProcessMapper.insert(caseProcess);
        // TODO: 2021/5/18 给分派人推送消息
        if (StringUtils.isNotEmpty(ccUid)) {
            // TODO: 2021/5/18 给抄送人推送消息
        }

    }

    @Override
    public TIEmployeeVo autoAssign(JSONObject params) throws HssException {

        Map<String, Long> measureMap = new HashMap<>();
        if (StringUtils.isNotEmpty(params.getString("lng")) && StringUtils.isNotEmpty(params.getString("lat"))) {
            String lng = params.getString("lng");
            String lat = params.getString("lat");
            Integer radius = 0;
            List<CasesetSys> casesetSysList = iCasesetSysService.list();
            if (!casesetSysList.isEmpty()) {
                radius = null == casesetSysList.get(0).getRadius() ? 0 : casesetSysList.get(0).getRadius();
            }
            QueryWrapper<TlEmployee> tlEmployeeQueryWrapper = new QueryWrapper<>();
            List<TlEmployee> tlEmployeeList = tlEmployeeMapper.selectList(tlEmployeeQueryWrapper);
            for (TlEmployee tlEmployee : tlEmployeeList) {
                if (null != tlEmployee.getAddr()) {
                    String[] tlEmployeeStr = tlEmployee.getAddr().split(",");
                    Long measure = DistanceUtils.measureDistance(Double.parseDouble(tlEmployeeStr[0]), Double.parseDouble(tlEmployeeStr[1]), Double.parseDouble(lng), Double.parseDouble(lat));
                    if (measure <= radius) {
                        measureMap.put(tlEmployee.getId(), measure);
                    }
                }
            }
        }
        String employeeId = getMinNumber(measureMap);
        TlEmployee tlEmployee = tlEmployeeMapper.selectById(employeeId);
        TIEmployeeVo tiEmployeeVo = new TIEmployeeVo();
        if (null != tlEmployee && null != tlEmployee.getBindaccount()) {
            User user = userMapper.selectById(tlEmployee.getBindaccount());
            if (null != user) {
                tiEmployeeVo.setName(user.getName());
                tiEmployeeVo.setValue(user.getUid());
            }
        }
        return tiEmployeeVo;
    }


    private String getMinNumber(Map<String, Long> measureMap) {
        String empId = "";
        List<Long> measureList = new ArrayList<>();
        for (String key : measureMap.keySet()) {
            measureList.add(measureMap.get(key));
        }
        if (!measureList.isEmpty()) {
            Long minNumber = Collections.min(measureList);
            for (String key : measureMap.keySet()) {
                if (minNumber.equals(measureMap.get(key))) {
                    empId = key;
                }
            }
        }
        return empId;
    }

    @Override
    @Transactional
    public void qiandao(JSONObject params) throws HssException {

        String uid = LoginUtils.getUser().getUid();
        String account = LoginUtils.getUser().getAccount();
        if (StringUtils.isEmpty(params) || StringUtils.isEmpty(params.getString("caseId"))) {
            throw new HssException("参数错误");
        }
        if (StringUtils.isEmpty(params) || StringUtils.isEmpty(params.getString("lng"))) {
            throw new HssException("参数错误");
        }
        if (StringUtils.isEmpty(params) || StringUtils.isEmpty(params.getString("lat"))) {
            throw new HssException("参数错误");
        }
        if (StringUtils.isEmpty(params) || StringUtils.isEmpty(params.getString("address"))) {
            throw new HssException("参数错误");
        }
        String caseId = params.getString("caseId");
        String lat = params.getString("lat");
        String lng = params.getString("lng");
        String address = params.getString("address");

        Cases cases = casesMapper.selectById(caseId);
        if (StringUtils.isEmpty(cases)) {
            throw new HssException("不存在的案件");
        }
        if (!uid.equals(cases.getPersonId())) {
            throw new HssException("请不要签到非本人工单");
        }
        if (1 == cases.getIsArchive()) {
            throw new HssException("案件已归档，不能操作！");
        }
        if (5 == cases.getStatus()) {
            throw new HssException("该案件已废弃，不能操作！");
        }
        if (4 == cases.getStatus()) {
            throw new HssException("该案件已结案，不能操作");
        }

        CaseProcess caseProcess = new CaseProcess();
        caseProcess.setCaseId(caseId);
        caseProcess.setHandle("签到");
        caseProcess.setCreateUid(uid);
        caseProcess.setCreateAccount(account);
        QueryWrapper<CaseProcess> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.lambda().eq(CaseProcess::getCaseId, caseId);
        queryWrapper1.lambda().orderByDesc(CaseProcess::getCreateTime);
        queryWrapper1.lambda().ne(CaseProcess::getHandle, "催办");
        queryWrapper1.lambda().last("limit 1");
        CaseProcess caseProcess1 = caseProcessMapper.selectOne(queryWrapper1);
        if (StringUtils.isNotEmpty(caseProcess1) && StringUtils.isNotEmpty(caseProcess1.getCreateTime())) {
            caseProcess.setCosttimedetail(StringUtils.subDate(caseProcess1.getCreateTime()));
        }
        caseProcess.setLat(lat);
        caseProcess.setLng(lng);
        caseProcess.setAddress(address);
        caseProcessMapper.insert(caseProcess);
        cases.setCaseId(caseId);
        cases.setSign(1);
        casesMapper.updateById(cases);
    }

    @Override
    public JSONObject getZrjgtjSjfbSjlyChart(JSONObject params) throws HssException {
        JSONObject json = new JSONObject();
        List<CasesListzrjgsjfbRes> casesList = casesMapper.getZrjgtjSjfbSjly(params);
        json.put("list", casesList);
        return json;
    }

    @Override
    public JSONObject getZrjgtjSjfbSjlyList(JSONObject params) throws HssException {
        JSONObject json = new JSONObject();
        Long page = StringUtils.isEmpty(params.getLong("page")) ? 1 : params.getLong("page");
        Long size = StringUtils.isEmpty(params.getLong("size")) ? 10 : params.getLong("size");
        Page<CasesListzrjgsjfbRes> pageCase = new Page<>(page, size, true);
        IPage<CasesListzrjgsjfbRes> iPage = casesMapper.getZrjgtjSjfbSjly(pageCase, params);
        json.put("total", iPage.getTotal());
        json.put("size", iPage.getSize());
        json.put("pages", iPage.getPages());
        json.put("current", iPage.getCurrent());
        json.put("list", iPage.getRecords());
        return json;
    }

    @Override
    public JSONObject getZrjgtjSjfbWtlxChart(JSONObject params) throws HssException {
        JSONObject json = new JSONObject();
        List<CasesListzrjgsjfbRes> casesList = casesMapper.getZrjgtjSjfbWtlx(params);
        json.put("list", casesList);
        return json;
    }

    @Override
    public JSONObject getZrjgtjSjfbWtlxList(JSONObject params) throws HssException {
        JSONObject json = new JSONObject();
        Long page = StringUtils.isEmpty(params.getLong("page")) ? 1 : params.getLong("page");
        Long size = StringUtils.isEmpty(params.getLong("size")) ? 10 : params.getLong("size");
        Page<CasesListzrjgsjfbRes> pageCase = new Page<>(page, size, true);
        IPage<CasesListzrjgsjfbRes> iPage = casesMapper.getZrjgtjSjfbWtlx(pageCase, params);
        json.put("total", iPage.getTotal());
        json.put("size", iPage.getSize());
        json.put("pages", iPage.getPages());
        json.put("current", iPage.getCurrent());
        json.put("list", iPage.getRecords());
        return json;
    }

    @Override
    public JSONObject getZrjgtjSjfbSjzsChart(JSONObject params) throws HssException {
        JSONObject json = new JSONObject();
        List<CasesListzrjgsjfbRes> casesList = casesMapper.getZrjgtjSjfbSjzsChart(params);
        json.put("list", casesList);
        return json;
    }

    @Override
    public JSONObject getZrjgtjClqkChart(JSONObject params) throws HssException {
        JSONObject json = new JSONObject();
        List<CasesListzrjgclqkRes> casesList = casesMapper.getZrjgtjClqk(params);
        json.put("list", casesList);
        return json;
    }

    @Override
    public JSONObject getZrjgtjClqkList(JSONObject params) throws HssException {
        JSONObject json = new JSONObject();
        Long page = StringUtils.isEmpty(params.getLong("page")) ? 1 : params.getLong("page");
        Long size = StringUtils.isEmpty(params.getLong("size")) ? 10 : params.getLong("size");
        Page<CasesListzrjgclqkRes> pageCase = new Page<>(page, size, true);
        IPage<CasesListzrjgclqkRes> iPage = casesMapper.getZrjgtjClqk(pageCase, params);
        json.put("total", iPage.getTotal());
        json.put("size", iPage.getSize());
        json.put("pages", iPage.getPages());
        json.put("current", iPage.getCurrent());
        json.put("list", iPage.getRecords());
        return json;
    }

    @Override
    public JSONObject getZrjgtjCljsfxChart(JSONObject params) throws HssException {
        JSONObject json = new JSONObject();
        List<CasesListzrjgcljsfxRes> casesList = casesMapper.getZrjgtjCljsfx(params);
        json.put("list", casesList);
        return json;
    }

    @Override
    public JSONObject getZrjgtjCljsfxList(JSONObject params) throws HssException {
        JSONObject json = new JSONObject();
        Long page = StringUtils.isEmpty(params.getLong("page")) ? 1 : params.getLong("page");
        Long size = StringUtils.isEmpty(params.getLong("size")) ? 10 : params.getLong("size");
        Page<CasesListzrjgcljsfxRes> pageCase = new Page<>(page, size, true);
        IPage<CasesListzrjgcljsfxRes> iPage = casesMapper.getZrjgtjCljsfx(pageCase, params);
        json.put("total", iPage.getTotal());
        json.put("size", iPage.getSize());
        json.put("pages", iPage.getPages());
        json.put("current", iPage.getCurrent());
        json.put("list", iPage.getRecords());
        return json;
    }

    /**
     * 事件分布 问题类型柱状图
     *
     * @param eventDistributionTO
     * @return java.util.List<java.util.List < java.lang.Object>>
     * @author zcy
     * @date 2021/10/15 13:52
     */
    @Override
    public List<List<Object>> getProblemTypeHistogramEChars(EventDistributionTO eventDistributionTO) {
        QueryWrapper<Cases> casesQueryWrapper = new QueryWrapper<>();
        Integer[] integers = {1, 2, 3, 4, 5};
        casesQueryWrapper.lambda().in(Cases::getStatus, integers);
        List<Cases> casesList = getCaseList(eventDistributionTO, casesQueryWrapper);
        List<BTable> problemTypeHistogramBTableList = buildProblemTypeHistogramBTable(casesList);
        fillDepId(casesList);
        return Tools.getBTable(problemTypeHistogramBTableList);
    }

    /**
     * 处理情况统计图
     *
     * @param eventDistributionTO
     * @return java.util.List<java.util.List < java.lang.Object>>
     * @author zcy
     * @date 2021/10/15 13:52
     */
    @Override
    public List<List<Object>> getTreatmentEChars(EventDistributionTO eventDistributionTO) throws ParseException {
        QueryWrapper<Cases> casesQueryWrapper = new QueryWrapper<>();
        Integer[] integers = {1, 2, 3, 4, 5};
        casesQueryWrapper.lambda().in(Cases::getStatus, integers);
        List<Cases> casesList = getCaseList(eventDistributionTO, casesQueryWrapper);
        fillDepId(casesList);
        return buildTreatmentResultList(casesList, eventDistributionTO);
    }

    private void fillDepId(List<Cases> casesList) {
        for (Cases cases : casesList) {
            if (StringUtils.isEmpty(cases.getDepid())) {
                cases.setDepid("");
            }
        }
    }

    /**
     * 处理及时分析统计图
     *
     * @param eventDistributionTO
     * @return java.util.List<java.util.List < java.lang.Object>>
     * @author zcy
     * @date 2021/10/15 13:52
     */
    @Override
    public List<List<Object>> getTimelyAnalysisEChars(EventDistributionTO eventDistributionTO) throws ParseException {
        QueryWrapper<Cases> casesQueryWrapper = new QueryWrapper<>();
        Integer[] integers = {1, 2, 3, 4, 5};
        casesQueryWrapper.lambda().in(Cases::getStatus, integers);
        List<Cases> casesList = getCaseList(eventDistributionTO, casesQueryWrapper);
        fillDepId(casesList);
        return buildTimelyAnalysisResultList(casesList, eventDistributionTO);
    }

    /**
     * 处理及时分析
     *
     * @param casesList
     * @param eventDistributionTO
     * @return java.util.List<java.util.List < java.lang.Object>>
     * @author zcy
     * @date 2021/10/15 13:52
     */
    private List<List<Object>> buildTimelyAnalysisResultList(List<Cases> casesList, EventDistributionTO eventDistributionTO) throws ParseException {

        Map<String, List<Cases>> casesMap = new HashMap<>();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat monthFormat = new SimpleDateFormat("yyyy-MM");
        Date startDate = eventDistributionTO.getStartDate();
        Date endDate = eventDistributionTO.getEndDate();
        Integer dateType = eventDistributionTO.getDateType();
        for (Cases cases : casesList) {
            if (Objects.nonNull(cases.getCreateTime())) {
                cases.setCreateDate(dateFormat.format(cases.getCreateTime()));
            }
            if (Objects.nonNull(cases.getCreateTime())) {
                cases.setCreateMonth(monthFormat.format(cases.getCreateTime()));
            }
        }
        List<String> dateList = null;
        if (dateType.equals(2)) {
            dateList = Tools.getMonthList(monthFormat, startDate, endDate);
            casesMap = GroupingByUtils.getGroupingForMapList(casesList, Cases::getCreateMonth);
        } else {
            dateList = Tools.getDateList(dateFormat, startDate, endDate);
            casesMap = GroupingByUtils.getGroupingForMapList(casesList, Cases::getCreateDate);
        }
        List<List<Object>> resultList = new ArrayList<>();
        List<Object> result = new ArrayList<>();
        Integer allCount = 0;
        //逾期
        Integer overdueCount = 0;
        //未逾期
        Integer unOverdueCount = 0;
        for (String date : dateList) {
            allCount = 0;
            //逾期
            overdueCount = 0;
            unOverdueCount = 0;
            result.add(date);
            if (casesMap.containsKey(date)) {
                for (Cases cases : casesMap.get(date)) {
                    allCount++;
                    if (cases.getIsOverdue().equals(1)) {
                        overdueCount++;
                    }
                    if (cases.getIsOverdue().equals(0)) {
                        unOverdueCount++;
                    }
                }
            }
            result.add(allCount);
            result.add(overdueCount);
            result.add(unOverdueCount);
            resultList.add(result);
            result = new ArrayList<>();
        }
        return resultList;
    }

    /**
     * 处理情况列表
     *
     * @param eventDistributionTO
     * @return java.util.List<java.util.List < java.lang.Object>>
     * @author zcy
     * @date 2021/10/15 13:52
     */
    @Override
    public TableDataInfo getTreatmentTable(EventDistributionTO eventDistributionTO) {
        QueryWrapper<Cases> casesQueryWrapper = new QueryWrapper<>();
        Integer[] integers = {1, 2, 3, 4, 5};
        casesQueryWrapper.lambda().in(Cases::getStatus, integers);
        List<Cases> casesList = getCaseList(eventDistributionTO, casesQueryWrapper);
        fillDepId(casesList);
        return buildTreatmentTableDataInfo(casesList, eventDistributionTO);
    }

    /**
     * 处理情况列表(按责任机构统计)分页后返回
     *
     * @param casesList
     * @param eventDistributionTO
     * @return
     */
    private TableDataInfo buildTreatmentTableDataInfo(List<Cases> casesList, EventDistributionTO eventDistributionTO) {
        List<TreatmentTableVO> treatmentTableVOList = getTreatmentTableVOList(casesList);
        return Tools.buildTableDataInfo(eventDistributionTO.getPage(), eventDistributionTO.getSize(), treatmentTableVOList);
    }

    /**
     * 处理情况列表(按责任机构统计)全数据List
     *
     * @param casesList
     * @return
     */
    private List<TreatmentTableVO> getTreatmentTableVOList(List<Cases> casesList) {
        List<TreatmentTableVO> treatmentTableVOList = new ArrayList<>();
        Map<String, List<Cases>> casesMap = GroupingByUtils.getGroupingForMapList(casesList, Cases::getDepid);
        Map<String, SysDepart> departMap = departService.getDepartMap(new QueryWrapper<>());
        Map<String, User> userMap = userService.getUserMap();
        //应处理数量
        Integer eventsShouldHandledCount = 0;
        //实际处理数量
        Integer eventsActualHandledCount = 0;
        //未结案数量
        Integer openCaseCount = 0;
        //实际处理率
        BigDecimal eventsActualHandledRate = BigDecimal.ZERO;
        SysDepart depart = null;
        for (String depId : casesMap.keySet()) {
            //应处理数量
            eventsShouldHandledCount = 0;
            //实际处理数量
            eventsActualHandledCount = 0;
            //未结案数量
            openCaseCount = 0;
            //实际处理率
            eventsActualHandledRate = BigDecimal.ZERO;
            depart = departMap.get(depId);
            for (Cases cases : casesMap.get(depId)) {
                eventsShouldHandledCount++;
                if (cases.getStatus().equals(3) || cases.getStatus().equals(4)) {
                    eventsActualHandledCount++;
                }
                if (cases.getStatus().equals(1) || cases.getStatus().equals(2) || cases.getStatus().equals(3)) {
                    openCaseCount++;
                }
            }
            if (eventsShouldHandledCount > 0) {
                eventsActualHandledRate = new BigDecimal(eventsActualHandledCount).divide(
                        new BigDecimal(eventsShouldHandledCount), 2, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100));
            }
            treatmentTableVOList.add(new TreatmentTableVO(Objects.nonNull(depart) ? depart.getDepartName() : "",
                    Objects.nonNull(depart) ? depart.getOrgType() : "", Objects.nonNull(depart) ? userMap.get(depart.getPrincipalUid()).getName() : ""
                    , eventsShouldHandledCount, eventsActualHandledCount, openCaseCount, eventsActualHandledRate));
        }
        return treatmentTableVOList;
    }

    /**
     * 及时处理列表
     *
     * @param eventDistributionTO
     * @return java.util.List<java.util.List < java.lang.Object>>
     * @author zcy
     * @date 2021/10/15 13:52
     */
    @Override
    public TableDataInfo getTimelyAnalysisTable(EventDistributionTO eventDistributionTO) {
        QueryWrapper<Cases> casesQueryWrapper = new QueryWrapper<>();
        Integer[] integers = {1, 2, 3, 4, 5};
        casesQueryWrapper.lambda().in(Cases::getStatus, integers);
        List<Cases> casesList = getCaseList(eventDistributionTO, casesQueryWrapper);
        fillDepId(casesList);
        return buildTimelyAnalysisTableDataInfo(casesList, eventDistributionTO);
    }

    /**
     * 及时分析列表(按责任机构统计)分页后数据
     *
     * @param casesList
     * @param eventDistributionTO
     * @return
     */
    private TableDataInfo buildTimelyAnalysisTableDataInfo(List<Cases> casesList, EventDistributionTO eventDistributionTO) {
        List<TimelyAnalysisTableVO> treatmentTableVOList = getTimelyAnalysisTableVOList(casesList);
        return Tools.buildTableDataInfo(eventDistributionTO.getPage(), eventDistributionTO.getSize(), treatmentTableVOList);
    }

    /**
     * 及时分析列表(按责任机构统计)全数据List
     *
     * @param casesList
     * @return
     */
    private List<TimelyAnalysisTableVO> getTimelyAnalysisTableVOList(List<Cases> casesList) {
        List<TimelyAnalysisTableVO> treatmentTableVOList = new ArrayList<>();
        Map<String, List<Cases>> casesMap = GroupingByUtils.getGroupingForMapList(casesList, Cases::getDepid);
        Map<String, SysDepart> departMap = departService.getDepartMap(new QueryWrapper<>());
        Map<String, User> userMap = userService.getUserMap();
        //应处理数量
        Integer eventsShouldHandledCount = 0;
        //实际处理数量
        Integer eventsActualHandledCount = 0;
        //及时处理数量
        Integer timelyAnalysisCount = 0;
        //逾期处理数量
        Integer unTimelyAnalysisCount = 0;
        //逾期处理率
        BigDecimal unTimelyAnalysisRate = BigDecimal.ZERO;
        //及时处理率
        BigDecimal timelyAnalysisRate = BigDecimal.ZERO;
        SysDepart depart = null;
        for (String depId : casesMap.keySet()) {
            String caseIds = "";
            //应处理数量
            eventsShouldHandledCount = 0;
            //实际处理数量
            eventsActualHandledCount = 0;
            //及时处理数量
            timelyAnalysisCount = 0;
            //逾期处理数量
            unTimelyAnalysisCount = 0;
            //逾期处理率
            unTimelyAnalysisRate = BigDecimal.ZERO;
            //及时处理率
            timelyAnalysisRate = BigDecimal.ZERO;
            depart = departMap.get(depId);
            for (Cases cases : casesMap.get(depId)) {
                if (StringUtils.isNotEmpty(caseIds)) {
                    caseIds = caseIds + "," + cases.getCaseId();
                } else {
                    caseIds = cases.getCaseId();
                }
                eventsShouldHandledCount++;
                if (cases.getStatus().equals(3) || cases.getStatus().equals(4)) {
                    eventsActualHandledCount++;
                }
                if ((cases.getIsOverdue().equals(0) && cases.getStatus().equals(4)) || (cases.getIsOverdue().equals(0) && cases.getStatus().equals(3))) {
                    timelyAnalysisCount++;
                }
                if ((cases.getIsOverdue().equals(1) && cases.getStatus().equals(4)) || (cases.getIsOverdue().equals(1) && cases.getStatus().equals(3))) {
                    unTimelyAnalysisCount++;
                }
            }
            if (eventsShouldHandledCount > 0) {
                unTimelyAnalysisRate = new BigDecimal(unTimelyAnalysisCount).divide(
                        new BigDecimal(eventsShouldHandledCount), 2, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100));
                timelyAnalysisRate = new BigDecimal(timelyAnalysisCount).divide(
                        new BigDecimal(eventsShouldHandledCount), 2, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100));
            }
            treatmentTableVOList.add(new TimelyAnalysisTableVO(caseIds, "", Objects.nonNull(depart) ? depart.getDepartName() : "",
                    Objects.nonNull(depart) ? depart.getOrgType() : "", "", Objects.nonNull(depart) ? userMap.get(depart.getPrincipalUid()).getName() : ""
                    , eventsShouldHandledCount, eventsActualHandledCount, timelyAnalysisCount, unTimelyAnalysisCount, unTimelyAnalysisRate, timelyAnalysisRate));
        }
        return treatmentTableVOList;
    }

    /**
     * @param casesList
     * @param eventDistributionTO
     * @return com.hskn.hss.core.page.TableDataInfo
     * @author zcy
     * @date 2021/10/20 13:34
     */
    private TableDataInfo buildTimelyAnalysisTableDataInfoByPersonId(List<Cases> casesList, EventDistributionTO eventDistributionTO) {
        List<TimelyAnalysisTableVO> treatmentTableVOList = getTimelyAnalysisTableVOS(casesList);
        return Tools.buildTableDataInfo(eventDistributionTO.getPageNum(), eventDistributionTO.getPageSize(), treatmentTableVOList);
    }

    private List<TimelyAnalysisTableVO> getTimelyAnalysisTableVOS(List<Cases> casesList) {
        List<TimelyAnalysisTableVO> treatmentTableVOList = new ArrayList<>();
        Map<String, List<Cases>> casesMap = GroupingByUtils.getGroupingForMapList(casesList, Cases::getPersonId);
        Map<String, SysDepart> departMap = departService.getDepartMap(new QueryWrapper<>());
        Map<String, User> userMap = userService.getUserMap();
        //应处理数量
        Integer eventsShouldHandledCount = 0;
        //实际处理数量
        Integer eventsActualHandledCount = 0;
        //及时处理数量
        Integer timelyAnalysisCount = 0;
        //逾期处理数量
        Integer unTimelyAnalysisCount = 0;
        //逾期处理率
        BigDecimal unTimelyAnalysisRate = BigDecimal.ZERO;
        //及时处理率
        BigDecimal timelyAnalysisRate = BigDecimal.ZERO;
        for (String personId : casesMap.keySet()) {
            String personName = "";
            String depName = "";
            String caseIds = "";
            String personIds = "";
            //应处理数量
            eventsShouldHandledCount = 0;
            //实际处理数量
            eventsActualHandledCount = 0;
            //及时处理数量
            timelyAnalysisCount = 0;
            //逾期处理数量
            unTimelyAnalysisCount = 0;
            //逾期处理率
            unTimelyAnalysisRate = BigDecimal.ZERO;
            //及时处理率
            timelyAnalysisRate = BigDecimal.ZERO;
            for (Cases cases : casesMap.get(personId)) {
                if (StringUtils.isNotEmpty(cases.getDepName()) && StringUtils.isEmpty(depName)) {
                    depName = cases.getDepName();
                    personIds = cases.getPersonId();
                }
                if (StringUtils.isNotEmpty(cases.getPersonName()) && StringUtils.isEmpty(personName)) {
                    personName = cases.getPersonName();
                }
                if (StringUtils.isNotEmpty(caseIds)) {
                    caseIds = caseIds + "," + cases.getCaseId();
                } else {
                    caseIds = cases.getCaseId();
                }
                eventsShouldHandledCount++;
                if (cases.getStatus().equals(3) || cases.getStatus().equals(4)) {
                    eventsActualHandledCount++;
                }
                if ((cases.getIsOverdue().equals(0) && cases.getStatus().equals(4)) || (cases.getIsOverdue().equals(0) && cases.getStatus().equals(3))) {
                    timelyAnalysisCount++;
                }
                if ((cases.getIsOverdue().equals(1) && cases.getStatus().equals(4)) || (cases.getIsOverdue().equals(1) && cases.getStatus().equals(3))) {
                    unTimelyAnalysisCount++;
                }
            }
            if (eventsShouldHandledCount > 0) {
                unTimelyAnalysisRate = new BigDecimal(unTimelyAnalysisCount).divide(
                        new BigDecimal(eventsShouldHandledCount), 2, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100));
                timelyAnalysisRate = new BigDecimal(timelyAnalysisCount).divide(
                        new BigDecimal(eventsShouldHandledCount), 2, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100));
            }
            treatmentTableVOList.add(new TimelyAnalysisTableVO(caseIds, personName, depName, "", personIds, ""
                    , eventsShouldHandledCount, eventsActualHandledCount, timelyAnalysisCount, unTimelyAnalysisCount, unTimelyAnalysisRate, timelyAnalysisRate));
        }
        return treatmentTableVOList;
    }

    /**
     * 处理情况统计图
     *
     * @param casesList
     * @return java.util.List<java.util.List < java.lang.Object>>
     * @author zcy
     * @date 2021/10/15 13:52
     */
    private List<List<Object>> buildTreatmentResultList(List<Cases> casesList, EventDistributionTO eventDistributionTO) throws ParseException {
        Integer dateType = eventDistributionTO.getDateType();
        for (Cases cases : casesList) {
            if (Objects.nonNull(cases.getCreateTime())) {
                cases.setCreateDate(Tools.getYearMonthDayString((cases.getCreateTime())));
            }
            if (Objects.nonNull(cases.getCreateTime())) {
                cases.setCreateMonth(Tools.getYearMonthString((cases.getCreateTime())));
            }
        }
        Map<String, List<Cases>> casesMap = new HashMap<>();
        if (dateType.equals(2)) {
            casesMap = GroupingByUtils.getGroupingForMapList(casesList, Cases::getCreateMonth);
        } else {
            casesMap = GroupingByUtils.getGroupingForMapList(casesList, Cases::getCreateDate);
        }
        return buildTreatmentResult(casesMap, eventDistributionTO);
    }

    /**
     * 处理情况
     *
     * @param casesMap
     * @return java.util.List<java.util.List < java.lang.Object>>
     * @author zcy
     * @date 2021/10/15 13:52
     */
    private List<List<Object>> buildTreatmentResult(Map<String, List<Cases>> casesMap, EventDistributionTO eventDistributionTO) throws ParseException {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat monthFormat = new SimpleDateFormat("yyyy-MM");
        Date startDate = eventDistributionTO.getStartDate();
        Date endDate = eventDistributionTO.getEndDate();
        Integer dateType = eventDistributionTO.getDateType();
        List<String> dateList = null;
        if (dateType.equals(2)) {
            dateList = Tools.getMonthList(monthFormat, startDate, endDate);
        } else {
            dateList = Tools.getDateList(dateFormat, startDate, endDate);
        }
        List<List<Object>> resultList = new ArrayList<>();
        List<Object> result = new ArrayList<>();
        Integer allCount = 0;
        //待指派
        Integer toDistributedCount = 0;
        //待处理
        Integer toPendCount = 0;
        //待结案
        Integer pendedCase = 0;
        //已结案
        Integer closedCaseCount = 0;
        //已废弃
        Integer obsoleteCount = 0;

        for (String date : dateList) {
            allCount = 0;
            //待指派
            toDistributedCount = 0;
            //待处理
            toPendCount = 0;
            //待结案
            pendedCase = 0;
            //已结案
            closedCaseCount = 0;
            //已废弃
            obsoleteCount = 0;
            result.add(date);
            if (casesMap.containsKey(date)) {
                for (Cases cases : casesMap.get(date)) {
                    allCount++;
                    if (cases.getStatus().equals(1)) {
                        toDistributedCount++;
                    }
                    if (cases.getStatus().equals(2)) {
                        toPendCount++;
                    }
                    if (cases.getStatus().equals(3)) {
                        pendedCase++;
                    }
                    if (cases.getStatus().equals(4)) {
                        closedCaseCount++;
                    }
                    if (cases.getStatus().equals(5)) {
                        obsoleteCount++;
                    }
                }
            }
            result.add(allCount);
            result.add(toDistributedCount);
            result.add(toPendCount);
            result.add(pendedCase);
            result.add(closedCaseCount);
            result.add(obsoleteCount);
            resultList.add(result);
            result = new ArrayList<>();
        }
        return resultList;
    }

    /**
     * 事件分布 时间走势折线图
     *
     * @param eventDistributionTO
     * @return java.util.List<java.util.List < java.lang.Object>>
     * @author zcy
     * @date 2021/10/15 13:52
     */
    @Override
    public List<List<Object>> getDistributionTimeTrendEChars(EventDistributionTO eventDistributionTO) throws ParseException {
        QueryWrapper<Cases> casesQueryWrapper = new QueryWrapper<>();
        Integer[] integers = {1, 2, 3, 4, 5};
        casesQueryWrapper.lambda().in(Cases::getStatus, integers);
        List<Cases> casesList = getCaseList(eventDistributionTO, casesQueryWrapper);
        List<BTable> distributionTimeTrendBTableList = buildDistributionTimeTrendBTable(casesList);
        fillDepId(casesList);
        return Tools.getDateEcharts(distributionTimeTrendBTableList, eventDistributionTO.getStartDate(), eventDistributionTO.getEndDate());
    }

    /**
     * 事件分布分组构造 问题类型柱状图
     *
     * @param casesList
     * @return java.util.List<com.hskn.hss.utils.BTable>
     * @author zcy
     * @date 2021/10/15 13:53
     */
    private List<BTable> buildProblemTypeHistogramBTable(List<Cases> casesList) {
        if (Objects.isNull(casesList)) {
            return new ArrayList<BTable>();
        }
        return getBTables(GroupingByUtils.getGroupingForMapList(casesList, Cases::getCaseIssueChildName));
    }

    /**
     * 事件分布分组构造 时间走势图
     *
     * @param casesList
     * @return java.util.List<com.hskn.hss.utils.BTable>
     * @author zcy
     * @date 2021/10/15 13:53
     */
    private List<BTable> buildDistributionTimeTrendBTable(List<Cases> casesList) {
        if (Objects.isNull(casesList)) {
            return new ArrayList<BTable>();
        }
        for (Cases cases : casesList) {
            if (Objects.nonNull(cases.getCreateTime())) {
                cases.setCreateDate(Tools.getYearMonthDayString((cases.getCreateTime())));
            }
        }
        return getBTables(GroupingByUtils.getGroupingForMapList(casesList, Cases::getCreateDate));
    }

    /**
     * 事件分布 来源统计
     *
     * @param eventDistributionTO
     * @return java.util.List<com.hskn.hss.utils.BTable>
     * @author zcy
     * @date 2021/10/15 13:53
     */
    @Override
    public TableDataInfo getProblemSourceTable(EventDistributionTO eventDistributionTO) {
        QueryWrapper<Cases> casesQueryWrapper = new QueryWrapper<>();
        Integer[] integers = {1, 2, 3, 4, 5};
        casesQueryWrapper.lambda().in(Cases::getStatus, integers);
        List<Cases> casesList = getCaseList(eventDistributionTO, casesQueryWrapper);
        fillDepId(casesList);
        return buildProblemSourceVOList(casesList, eventDistributionTO);
    }

    /**
     * 事件分布 问题类型
     *
     * @param eventDistributionTO
     * @return java.util.List<com.hskn.hss.utils.BTable>
     * @author zcy
     * @date 2021/10/15 13:53
     */
    @Override
    public TableDataInfo getProblemTypeTableVOTable(EventDistributionTO eventDistributionTO) {
        QueryWrapper<Cases> casesQueryWrapper = new QueryWrapper<>();
        Integer[] integers = {1, 2, 3, 4, 5};
        casesQueryWrapper.lambda().in(Cases::getStatus, integers);
        List<Cases> casesList = getCaseList(eventDistributionTO, casesQueryWrapper);
        fillDepId(casesList);
        return buildProblemTypeTableVOList(casesList, eventDistributionTO);
    }

    /**
     * 事件分布 来源统计 构造数据列表
     *
     * @param casesList
     * @return java.util.List<com.hskn.hss.module.cases.vo.ProblemSourceVO>
     * @author zcy
     * @date 2021/10/15 16:16
     */
    private TableDataInfo buildProblemSourceVOList(List<Cases> casesList, EventDistributionTO eventDistributionTO) {
        if (Objects.isNull(casesList)) {
            return new TableDataInfo();
        }
        List<ProblemSourceVO> problemSourceVOList = new ArrayList<ProblemSourceVO>();
        Map<String, SysDepart> departMap = departService.getDepartMap(new QueryWrapper<>());
        Map<String, User> userMap = userService.getUserMap();
        Map<String, SysUserDepart> userDepartMap = userDepartService.getUserDepart();
//        QueryWrapper<TlEmployee> employeeQueryWrapper = new QueryWrapper<>();
//        employeeQueryWrapper.lambda().isNotNull(TlEmployee::getBindaccount);
//        List<TlEmployee> employeeList = tlEmployeeMapper.selectList(employeeQueryWrapper);
//        Map<String, TlEmployee> employeeMap = GroupingByUtils.getGroupingForMapEntity(employeeList, TlEmployee::getBindaccount,
//                Collectors.collectingAndThen(Collectors.toList(), value -> value.get(0)));
        for (Cases cases : casesList) {
            if (StringUtils.isNotEmpty(cases.getCreateUid())) {
                User user = null;
                if (Objects.nonNull(cases) && userMap.containsKey(cases.getCreateUid())) {
                    user = userMap.get(cases.getCreateUid());
                }
//                TlEmployee employee = null;
//                if (Objects.nonNull(user) && employeeMap.containsKey(user.getUid())) {
//                    employee = employeeMap.get(user.getUid());
//                }
                SysUserDepart userDepart = null;
                if (Objects.nonNull(user) && userDepartMap.containsKey(user.getUid())) {
                    userDepart = userDepartMap.get(user.getUid());
                }
                SysDepart depart = null;
                if (Objects.nonNull(userDepart) && departMap.containsKey(userDepart.getDepid())) {
                    depart = departMap.get(userDepart.getDepid());
                    cases.setDepName(depart.getDepartName());
                    cases.setDepid(depart.getId());
                }
            }
        }
        Map<String, List<Cases>> casesMap = GroupingByUtils.getGroupingForMapList(casesList, Cases::getDepid);
        for (String depId : casesMap.keySet()) {
            problemSourceVOList.add(buildProblemSourceVO(casesMap.get(depId), departMap.get(depId), userMap));
        }
        return Tools.buildTableDataInfo(eventDistributionTO.getPage(), eventDistributionTO.getSize(), problemSourceVOList);
    }


    /**
     * 事件分布 问题类型 构造数据列表
     *
     * @param casesList
     * @return java.util.List<com.hskn.hss.module.cases.vo.ProblemSourceVO>
     * @author zcy
     * @date 2021/10/15 16:16
     */
    private TableDataInfo buildProblemTypeTableVOList(List<Cases> casesList, EventDistributionTO eventDistributionTO) {
        List<ProblemTypeTableVO> problemTypeTableVOList = new ArrayList<ProblemTypeTableVO>();
        Map<String, SysDepart> departMap = departService.getDepartMap(new QueryWrapper<>());
        Map<String, User> userMap = userService.getUserMap();
        QueryWrapper<TlEmployee> employeeQueryWrapper = new QueryWrapper<>();
        employeeQueryWrapper.lambda().isNotNull(TlEmployee::getBindaccount);
        List<TlEmployee> employeeList = tlEmployeeMapper.selectList(employeeQueryWrapper);
        Map<String, TlEmployee> employeeMap = GroupingByUtils.getGroupingForMapEntity(employeeList, TlEmployee::getBindaccount,
                Collectors.collectingAndThen(Collectors.toList(), value -> value.get(0)));
        for (Cases cases : casesList) {
            if (StringUtils.isNotEmpty(cases.getCreateUid())) {
                User user = null;
                if (Objects.nonNull(cases) && userMap.containsKey(cases.getCreateUid())) {
                    user = userMap.get(cases.getCreateUid());
                }
                TlEmployee employee = null;
                if (Objects.nonNull(user) && employeeMap.containsKey(user.getUid())) {
                    employee = employeeMap.get(user.getUid());
                }
                SysDepart depart = null;
                if (Objects.nonNull(employee) && departMap.containsKey(employee.getDeptid())) {
                    depart = departMap.get(employee.getDeptid());
                    cases.setDepName(depart.getDepartName());
                    cases.setDepid(depart.getId());
                }

            }
        }
        Map<String, List<Cases>> casesMap = GroupingByUtils.getGroupingForMapList(casesList, Cases::getDepid);
        for (String depId : casesMap.keySet()) {
            problemTypeTableVOList.add(buildProblemTypeTableVO(casesMap.get(depId), departMap.get(depId), userMap));
        }
        return Tools.buildTableDataInfo(eventDistributionTO.getPage(), eventDistributionTO.getSize(), problemTypeTableVOList);
    }

    /**
     * 事件分布 来源统计 构造一条数据
     *
     * @param casesList
     * @param depart
     * @param userMap
     * @return com.hskn.hss.module.cases.vo.ProblemSourceVO
     * @author zcy
     * @date 2021/10/15 17:48
     */
    private ProblemSourceVO buildProblemSourceVO(List<Cases> casesList, SysDepart depart, Map<String, User> userMap) {
        ProblemSourceVO problemSourceVO = new ProblemSourceVO();
        if (Objects.nonNull(depart)) {
            problemSourceVO.setDepName(depart.getDepartName());
        }
        if (Objects.nonNull(depart)) {
            problemSourceVO.setDepType(depart.getOrgType());
        }
        if (Objects.nonNull(depart)) {
            problemSourceVO.setExecutiveDirector(userMap.get(depart.getPrincipalUid()).getName());
        }
        if (Objects.nonNull(depart)) {
            problemSourceVO.setCasesCount(casesList.size());
        }
        return problemSourceVO;
    }

    /**
     * 事件分布 来源统计 构造一条数据
     *
     * @param casesList
     * @param depart
     * @param userMap
     * @return com.hskn.hss.module.cases.vo.ProblemSourceVO
     * @author zcy
     * @date 2021/10/15 17:48
     */
    private ProblemTypeTableVO buildProblemTypeTableVO(List<Cases> casesList, SysDepart depart, Map<String, User> userMap) {
        ProblemTypeTableVO problemTypeTableVO = new ProblemTypeTableVO();
        if (Objects.nonNull(depart)) {
            problemTypeTableVO.setDepName(depart.getDepartName());
        }
        if (Objects.nonNull(depart)) {
            problemTypeTableVO.setDepType(depart.getOrgType());
        }
        if (Objects.nonNull(depart)) {
            problemTypeTableVO.setExecutiveDirector(userMap.get(depart.getPrincipalUid()).getName());
        }
        if (Objects.nonNull(casesList)) {
            problemTypeTableVO.setAllCount(casesList.size());
        }
        //道路不洁
        Integer roadUncleanCount = 0;
        //暴露垃圾
        Integer exposedGarbageCount = 0;
        //垃圾污染
        Integer garbagePollutionCount = 0;
        //其他
        Integer otherCount = 0;
        for (Cases cases : casesList) {
            if (cases.getCaseIssueChildName().equals("道路不洁")) {
                roadUncleanCount++;
            }
            if (cases.getCaseIssueChildName().equals("暴露垃圾")) {
                exposedGarbageCount++;
            }
            if (cases.getCaseIssueChildName().equals("垃圾污染")) {
                garbagePollutionCount++;
            }
        }
        otherCount = casesList.size() - roadUncleanCount - exposedGarbageCount - garbagePollutionCount;
        problemTypeTableVO.setRoadUncleanCount(roadUncleanCount);
        problemTypeTableVO.setExposedGarbageCount(exposedGarbageCount);
        problemTypeTableVO.setGarbagePollutionCount(garbagePollutionCount);
        problemTypeTableVO.setOtherCount(otherCount);
        return problemTypeTableVO;
    }

    /**
     * 构造List<BTable>
     *
     * @param groupingForMapList
     * @return java.util.List<com.hskn.hss.utils.BTable>
     * @author zcy
     * @date 2021/10/15 15:29
     */
    private List<BTable> getBTables(Map<String, List<Cases>> groupingForMapList) {
        List<BTable> bTableLst = new ArrayList<>();
        Map<String, List<Cases>> casesMap = groupingForMapList;
        for (String caseIssueChildName : casesMap.keySet()) {
            bTableLst.add(new BTable(caseIssueChildName, casesMap.get(caseIssueChildName).size()));
        }
        return bTableLst;
    }

    /**
     * 事件查询
     *
     * @param eventDistributionTO
     * @return java.util.List<com.hskn.hss.module.cases.entity.Cases>
     * @author zcy
     * @date 2021/10/15 13:54
     */
    private List<Cases> getCaseList(EventDistributionTO eventDistributionTO, QueryWrapper<Cases> casesQueryWrapper) {
        if (StringUtils.isNotEmpty(eventDistributionTO.getDepId())) {
            List<String> depIds = departService.getChildIdsByIId(eventDistributionTO.getDepId());
            casesQueryWrapper.lambda().in(Cases::getDepid, depIds);
        }
        if (StringUtils.isNotEmpty(eventDistributionTO.getDepType())) {
            QueryWrapper<SysDepart> departQueryWrapper = new QueryWrapper<>();
            departQueryWrapper.lambda().eq(SysDepart::getOrgType, eventDistributionTO.getDepType());
            Map<String, SysDepart> departMap = departService.getDepartMap(departQueryWrapper);
            casesQueryWrapper.lambda().in(Cases::getDepid, departMap.keySet());
        }
        if (StringUtils.isNotEmpty(eventDistributionTO.getUserId())) {
            casesQueryWrapper.lambda().eq(Cases::getCreateUid, eventDistributionTO.getUserId());
        }
        if (StringUtils.isNotEmpty(eventDistributionTO.getProblemCategoryId())) {
            casesQueryWrapper.lambda().eq(Cases::getCaseIssueId, eventDistributionTO.getProblemCategoryId());
        }
        if (StringUtils.isNotEmpty(eventDistributionTO.getProblemSubclassId())) {
            casesQueryWrapper.lambda().eq(Cases::getCaseIssueChildId, eventDistributionTO.getProblemSubclassId());
        }
        if (Objects.nonNull(eventDistributionTO.getStartDate()) && Objects.nonNull(eventDistributionTO.getEndDate())) {
            casesQueryWrapper.lambda().between(Cases::getCreateTime, Tools.getDateForBegin(eventDistributionTO.getStartDate()), Tools.getDateForEnd(eventDistributionTO.getEndDate()));
        }
        if (CollectionUtils.isNotEmpty(eventDistributionTO.getPersonIds())) {
            casesQueryWrapper.lambda().in(Cases::getPersonId, eventDistributionTO.getPersonIds());
        }
        return casesMapper.selectList(casesQueryWrapper);
    }


    @Override
    public List<List<Object>> selectCaseForLineChartBTable(Cases cases) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        List<BTable> res = new ArrayList<>();
        List<BTable> list = casesMapper.selectCaseForLineChartBTable(cases);
        List<String> dateList = null;
        if (cases.getStartDate() != null && cases.getEndDate() != null) {
            dateList = Tools.getBetweenDate(format.format(cases.getStartDate()), format.format(cases.getEndDate()));
        } else {
            dateList = Tools.getDayListOfMonth();
        }
        for (int i = 0; i < dateList.size(); i++) {
            res.add(new BTable(dateList.get(i)));
            for (BTable bTable : list) {
                res.get(i).setData(0);
                if (bTable.getTime().equals(dateList.get(i))) {
                    res.get(i).setData(bTable.getData());
                    break;
                }
            }
        }
        List<List<Object>> resList = new ArrayList<>();
        List<Object> ru = new ArrayList<>();
        for (BTable b : res) {
            ru.add(b.getTime());
            resList.add(ru);
            ru = new ArrayList<>();
        }
        resList = Tools.getBTable(resList, res);
        return resList;
    }

    @Override
    public List<CasesTable> selectCaseForDepartCount(Cases cases) {
        return casesMapper.selectCaseForDepartCount(cases);
    }

    @Override
    public List<CasesTable> selectCaseForcaseIssueCount(Cases cases) {
        return casesMapper.selectCaseForcaseIssueCount(cases);
    }

    @Override
    public List<CasesTable> selectCaseForOverCount(Cases cases) {
        return casesMapper.selectCaseForOverCount(cases);
    }

    @Override
    public List<CasesTable> selectCaseForTimelyAnalyse(Cases cases) {
        return casesMapper.selectCaseForTimelyAnalyse(cases);
    }

    @Override
    public List<List<Object>> selectCaseForOverBTable(Cases cases) {
        List<String> stringList = Arrays.asList(Cases.statusList.split(","));
        List<BTable> list = casesMapper.selectCaseForOverBTable(cases);
        List<BTable> res = new ArrayList<>();
        for (String str : stringList) {
            res.add(new BTable(str));
        }
        for (BTable bTable : list) {
            switch (bTable.getTime()) {
                case "1":
                    bTable.setTime(stringList.get(0));
                    break;
                case "2":
                    bTable.setTime(stringList.get(1));
                    break;
                case "3":
                    bTable.setTime(stringList.get(2));
                    break;
                case "4":
                    bTable.setTime(stringList.get(3));
                    break;
                case "5":
                    bTable.setTime(stringList.get(4));
                    break;
            }
            for (BTable bt : res) {
                if (bt.getTime().equals(bTable.getTime())) {
                    bt.setData(bTable.getData());
                } else {
                    bt.setData(0);
                }
            }
        }
        List<List<Object>> resList = new ArrayList<>();
        List<Object> ru = new ArrayList<>();
        for (BTable b : res) {
            ru.add(b.getTime());
            resList.add(ru);
            ru = new ArrayList<>();
        }
        resList = Tools.getBTable(resList, res);
        return resList;
    }

    @Override
    public List<List<Object>> eventPersonByType(Cases cases) {
        if (Objects.isNull(cases.getStartDate())) {
            cases.setStartDate(DateUtil.parseDateTime(DateUtil.format(new Date(), DatePattern.NORM_MONTH_PATTERN) + "-01 00:00:00"));
        } else {
            cases.setStartDate(DateUtil.parseDateTime(DateUtil.formatDate(cases.getStartDate()) + " 00:00:00"));
        }
        if (Objects.isNull(cases.getEndDate())) {
            cases.setEndDate(DateUtil.parseDateTime(DateUtil.formatDate(new Date()) + " 23:59:59"));
        } else {
            cases.setEndDate(DateUtil.parseDateTime(DateUtil.formatDate(cases.getEndDate()) + " 23:59:59"));
        }
        QueryWrapper<Cases> casesQueryWrapper = new QueryWrapper<>();
        casesQueryWrapper.lambda().ge(Cases::getCreateTime, cases.getStartDate());
        casesQueryWrapper.lambda().le(Cases::getCreateTime, cases.getEndDate());
        if (StringUtils.isNotEmpty(cases.getPersonId())) {
            casesQueryWrapper.lambda().eq(Cases::getPersonId, cases.getPersonId());
        }
        if (StringUtils.isNotEmpty(cases.getCreateUid())) {
            casesQueryWrapper.lambda().eq(Cases::getCreateUid, cases.getCreateUid());
        }
        if (StringUtils.isNotEmpty(cases.getCaseIssueId())) {
            casesQueryWrapper.lambda().eq(Cases::getCaseIssueId, cases.getCaseIssueId());
        }
        if (StringUtils.isNotEmpty(cases.getCaseIssueChildId())) {
            casesQueryWrapper.lambda().eq(Cases::getCaseIssueChildId, cases.getCaseIssueChildId());
        }
//        List<Integer> status = Arrays.asList(3, 4);
//        casesQueryWrapper.lambda().in(Cases::getStatus, status);
        List<Cases> cases1 = casesMapper.selectList(casesQueryWrapper);
        Map<String, List<Cases>> collect = cases1.stream().collect(Collectors.groupingBy(Cases::getCaseIssueChildName));

        List<List<Object>> resList = new ArrayList<>();

        collect.keySet().forEach(t -> {
            List<Object> ru = new ArrayList<>();
            ru.add(t);
            List<Cases> casesList = collect.get(t);
            ru.add(casesList.size());
            resList.add(ru);
        });
        return resList;
    }

    @Override
    public List<List<Object>> eventPersonByTime(Cases cases) {
        if (Objects.isNull(cases.getStartDate())) {
            cases.setStartDate(DateUtil.parseDateTime(DateUtil.format(new Date(), DatePattern.NORM_MONTH_PATTERN) + "-01 00:00:00"));
        } else {
            cases.setStartDate(DateUtil.parseDateTime(DateUtil.formatDate(cases.getStartDate()) + " 00:00:00"));
        }
        if (Objects.isNull(cases.getEndDate())) {
            cases.setEndDate(DateUtil.parseDateTime(DateUtil.formatDate(new Date()) + " 23:59:59"));
        } else {
            cases.setEndDate(DateUtil.parseDateTime(DateUtil.formatDate(cases.getEndDate()) + " 23:59:59"));
        }
        QueryWrapper<Cases> casesQueryWrapper = new QueryWrapper<>();
        casesQueryWrapper.lambda().ge(Cases::getCreateTime, cases.getStartDate());
        casesQueryWrapper.lambda().le(Cases::getCreateTime, cases.getEndDate());
        if (StringUtils.isNotEmpty(cases.getPersonId())) {
            casesQueryWrapper.lambda().eq(Cases::getPersonId, cases.getPersonId());
        }
        if (StringUtils.isNotEmpty(cases.getCreateUid())) {
            casesQueryWrapper.lambda().eq(Cases::getCreateUid, cases.getCreateUid());
        }
        if (StringUtils.isNotEmpty(cases.getCaseIssueId())) {
            casesQueryWrapper.lambda().eq(Cases::getCaseIssueId, cases.getCaseIssueId());
        }
        if (StringUtils.isNotEmpty(cases.getCaseIssueChildId())) {
            casesQueryWrapper.lambda().eq(Cases::getCaseIssueChildId, cases.getCaseIssueChildId());
        }
//        List<Integer> status = Arrays.asList(3, 4);
//        casesQueryWrapper.lambda().in(Cases::getStatus, status);
        List<Cases> cases1 = casesMapper.selectList(casesQueryWrapper);
        cases1.forEach(c -> {
            c.setCreateDate(DateUtil.formatDate(c.getCreateTime()));
        });
        TreeMap<String, List<Cases>> collect = cases1.stream().collect(Collectors.groupingBy(Cases::getCreateDate, TreeMap::new, Collectors.toList()));
        List<List<Object>> resList = new ArrayList<>();

        List<Date> betweenDateList = Tools.getBetweenDateList(DateUtil.formatDate(cases.getStartDate()), DateUtil.formatDate(cases.getEndDate()));
        betweenDateList.forEach(t -> {
            List<Object> ru = new ArrayList<>();
            ru.add(DateUtil.formatDate(t));
            ru.add(0);
            resList.add(ru);
        });

        collect.keySet().forEach(t -> {
            List<Object> ru = new ArrayList<>();
            ru.add(t);
            ru.add(0);
            int i = resList.indexOf(ru);

            List<Object> ru1 = new ArrayList<>();
            List<Cases> casesList = collect.get(t);
            ru1.add(t);
            ru1.add(casesList.size());
            resList.set(i, ru1);
        });
        return resList;
    }

    @Override
    public TableDataInfo eventPersonByCreater(Cases cases) {
        List<CasesTable> casesTables = getCasesTablesList(cases);
        return Tools.buildTableDataInfo(cases.getPageNum(), cases.getPageSize(), casesTables);
    }

    private List<CasesTable> getCasesTablesList(Cases cases) {
        if (Objects.isNull(cases.getStartDate())) {
            cases.setStartDate(DateUtil.parseDateTime(DateUtil.format(new Date(), DatePattern.NORM_MONTH_PATTERN) + "-01 00:00:00.0"));
        } else {
            cases.setStartDate(DateUtil.parseDateTime(DateUtil.formatDate(cases.getStartDate()) + " 00:00:00.0"));
        }
        if (Objects.isNull(cases.getEndDate())) {
            cases.setEndDate(DateUtil.parseDateTime(DateUtil.formatDate(new Date()) + " 23:59:59.999"));
        } else {
            cases.setEndDate(DateUtil.parseDateTime(DateUtil.formatDate(cases.getEndDate()) + " 23:59:59.999"));
        }
        if (StringUtils.isNotEmpty(cases.getDepid())) {
            List<String> depIds = departService.getChildIdsByIId(cases.getDepid());
            cases.setDepIds(depIds);
        }
        List<CasesTable> casesTables = casesMapper.eventPersonByCreater(cases);
        Map<String, SysUserDepart> userDepart = sysUserDepartService.getUserDepart();
        Map<String, SysDepart> departMap = departService.getDepartMap(new QueryWrapper<>());
        casesTables.forEach(t -> {
            SysUserDepart sysUserDepart = userDepart.get(t.getCreateUid());
            if (Objects.nonNull(sysUserDepart)) {
                SysDepart sysDepart = departMap.get(sysUserDepart.getDepid());
                t.setCreateDeptId(sysDepart.getId());
                t.setCreateDeptName(sysDepart.getDepartName());
            }
        });


        if (Objects.nonNull(casesTables) && casesTables.size() > 0) {
            QueryWrapper<Cases> casesQueryWrapper = new QueryWrapper<>();
            if (StringUtils.isNotEmpty(cases.getPersonId())) {
                casesQueryWrapper.lambda().eq(Cases::getPersonId, cases.getPersonId());
            }
            if (StringUtils.isNotEmpty(cases.getCreateUid())) {
                casesQueryWrapper.lambda().eq(Cases::getCreateUid, cases.getCreateUid());
            }
            if (StringUtils.isNotEmpty(cases.getCaseIssueId())) {
                casesQueryWrapper.lambda().eq(Cases::getCaseIssueId, cases.getCaseIssueId());
            }
            if (StringUtils.isNotEmpty(cases.getCaseIssueChildId())) {
                casesQueryWrapper.lambda().eq(Cases::getCaseIssueChildId, cases.getCaseIssueChildId());
            }
            if (CollectionUtils.isNotEmpty(cases.getCreateUids())) {
                casesQueryWrapper.lambda().in(Cases::getCreateUid, cases.getCreateUids());
            }

            casesQueryWrapper.lambda().ge(Cases::getCreateTime, cases.getStartDate());
            casesQueryWrapper.lambda().le(Cases::getCreateTime, cases.getEndDate());

            List<Cases> casesList = casesMapper.selectList(casesQueryWrapper);

            Map<String, List<Cases>> casesMap = casesList.stream().collect(Collectors.groupingBy(Cases::getCreateUid));

            Map<String, Map<Integer, List<Cases>>> map2 = new HashMap<>();
            casesMap.keySet().forEach(t -> {
                List<Cases> casess = casesMap.get(t);
                Map<Integer, List<Cases>> alarmTypeCarMap = casess.stream().collect(Collectors.groupingBy(Cases::getStatus));
                map2.put(casess.get(0).getCreateUid(), alarmTypeCarMap);
            });

            for (CasesTable casesTable : casesTables
            ) {
                if (map2.containsKey(casesTable.getCreateUid()) && Objects.nonNull(map2.get(casesTable.getCreateUid()).get(1))) {
                    casesTable.setOpenCount(casesTable.getOpenCount() + map2.get(casesTable.getCreateUid()).get(1).size());
                }
                if (map2.containsKey(casesTable.getCreateUid()) && Objects.nonNull(map2.get(casesTable.getCreateUid()).get(2))) {
                    casesTable.setOpenCount(casesTable.getOpenCount() + map2.get(casesTable.getCreateUid()).get(2).size());
                }
                if (map2.containsKey(casesTable.getCreateUid()) && Objects.nonNull(map2.get(casesTable.getCreateUid()).get(3))) {
                    casesTable.setOpenCount(casesTable.getOpenCount() + map2.get(casesTable.getCreateUid()).get(3).size());
                }
                if (map2.containsKey(casesTable.getCreateUid()) && Objects.nonNull(map2.get(casesTable.getCreateUid()).get(4))) {
                    casesTable.setClosedCount(map2.get(casesTable.getCreateUid()).get(4).size());
                }
            }
        }
        return casesTables;
    }

    /**
     * 按负责人统计-问题类型统计表格
     *
     * @param cases
     * @return
     */
    @Override
    public TableDataInfo eventPersonByProblem(Cases cases) {
        List<CasesTable> casesTables = getCasesTablesVO(cases);
        return Tools.buildTableDataInfo(cases.getPageNum(), cases.getPageSize(), casesTables);
    }

    private List<CasesTable> getCasesTablesVO(Cases cases) {
        if (Objects.isNull(cases.getStartDate())) {
            cases.setStartDate(DateUtil.parseDateTime(DateUtil.format(new Date(), DatePattern.NORM_MONTH_PATTERN) + "-01 00:00:00"));
        } else {
            cases.setStartDate(DateUtil.parseDateTime(DateUtil.formatDate(cases.getStartDate()) + " 00:00:00"));
        }
        if (Objects.isNull(cases.getEndDate())) {
            cases.setEndDate(DateUtil.parseDateTime(DateUtil.formatDate(new Date()) + " 23:59:59"));
        } else {
            cases.setEndDate(DateUtil.parseDateTime(DateUtil.formatDate(cases.getEndDate()) + " 23:59:59"));
        }
        List<CasesTable> casesTables = casesMapper.eventPersonByCreater(cases);
        Map<String, SysUserDepart> userDepart = sysUserDepartService.getUserDepart();
        Map<String, SysDepart> departMap = departService.getDepartMap(new QueryWrapper<>());
        casesTables.forEach(t -> {
            SysUserDepart sysUserDepart = userDepart.get(t.getCreateUid());
            if (Objects.nonNull(sysUserDepart)) {
                SysDepart sysDepart = departMap.get(sysUserDepart.getDepid());
                t.setCreateDeptId(sysDepart.getId());
                t.setCreateDeptName(sysDepart.getDepartName());
            }
        });

        if (Objects.nonNull(casesTables) && casesTables.size() > 0) {
            QueryWrapper<Cases> casesQueryWrapper = new QueryWrapper<>();
            if (StringUtils.isNotEmpty(cases.getPersonId())) {
                casesQueryWrapper.lambda().eq(Cases::getPersonId, cases.getPersonId());
            }
            if (StringUtils.isNotEmpty(cases.getCreateUid())) {
                casesQueryWrapper.lambda().eq(Cases::getCreateUid, cases.getCreateUid());
            }
            if (StringUtils.isNotEmpty(cases.getCaseIssueId())) {
                casesQueryWrapper.lambda().eq(Cases::getCaseIssueId, cases.getCaseIssueId());
            }
            if (StringUtils.isNotEmpty(cases.getCaseIssueChildId())) {
                casesQueryWrapper.lambda().eq(Cases::getCaseIssueChildId, cases.getCaseIssueChildId());
            }

            casesQueryWrapper.lambda().ge(Cases::getCreateTime, cases.getStartDate());
            casesQueryWrapper.lambda().le(Cases::getCreateTime, cases.getEndDate());

            List<Cases> casesList = casesMapper.selectList(casesQueryWrapper);

            Map<String, List<Cases>> casesMap = casesList.stream().collect(Collectors.groupingBy(Cases::getCreateUid));

            Map<String, Map<String, List<Cases>>> map2 = new HashMap<>();
            casesMap.keySet().forEach(t -> {
                List<Cases> casess = casesMap.get(t);
                Map<String, List<Cases>> alarmTypeCarMap = casess.stream().collect(Collectors.groupingBy(Cases::getCaseIssueChildName));
                map2.put(t, alarmTypeCarMap);
            });

            for (CasesTable casesTable : casesTables
            ) {
                if (Objects.nonNull(map2.get(casesTable.getCreateUid()).get("道路不洁"))) {
                    casesTable.setDlbjCount(map2.get(casesTable.getCreateUid()).get("道路不洁").size());
                }
                if (Objects.nonNull(map2.get(casesTable.getCreateUid()).get("暴露垃圾"))) {
                    casesTable.setBlljCount(map2.get(casesTable.getCreateUid()).get("暴露垃圾").size());
                }
                if (Objects.nonNull(map2.get(casesTable.getCreateUid()).get("绿地脏乱"))) {
                    casesTable.setLdzlCount(map2.get(casesTable.getCreateUid()).get("绿地脏乱").size());
                }
                if (Objects.nonNull(map2.get(casesTable.getCreateUid()).get("积存垃圾渣土"))) {
                    casesTable.setJcljztCount(map2.get(casesTable.getCreateUid()).get("积存垃圾渣土").size());
                }
                if (Objects.nonNull(map2.get(casesTable.getCreateUid()).get("道路遗撒"))) {
                    casesTable.setDlysCount(map2.get(casesTable.getCreateUid()).get("道路遗撒").size());
                }
                if (Objects.nonNull(map2.get(casesTable.getCreateUid()).get("水域不洁"))) {
                    casesTable.setSybjCount(map2.get(casesTable.getCreateUid()).get("水域不洁").size());
                }
                if (Objects.nonNull(map2.get(casesTable.getCreateUid()).get("油烟污染"))) {
                    casesTable.setYywrCount(map2.get(casesTable.getCreateUid()).get("油烟污染").size());
                }
                if (Objects.nonNull(map2.get(casesTable.getCreateUid()).get("动物尸体清理"))) {
                    casesTable.setDwstqlCount(map2.get(casesTable.getCreateUid()).get("动物尸体清理").size());
                }
            }
        }
        return casesTables;
    }

    @Override
    public TableDataInfo eventPersonTreatmentTable(Cases cases) {
        if (Objects.isNull(cases.getStartDate())) {
            cases.setStartDate(DateUtil.parseDateTime(DateUtil.format(new Date(), DatePattern.NORM_MONTH_PATTERN) + "-01 00:00:00"));
        } else {
            cases.setStartDate(DateUtil.parseDateTime(DateUtil.formatDate(cases.getStartDate()) + " 00:00:00"));
        }
        if (Objects.isNull(cases.getEndDate())) {
            cases.setEndDate(DateUtil.parseDateTime(DateUtil.formatDate(new Date()) + " 23:59:59"));
        } else {
            cases.setEndDate(DateUtil.parseDateTime(DateUtil.formatDate(cases.getEndDate()) + " 23:59:59"));
        }
        if (cases.getDepid() != null && cases.getDepid() != "") {
            List<String> depIds = departService.getChildIdsByIId(cases.getDepid());
            cases.setDepIds(depIds);
        }
        List<CasesTable> casesTables = casesMapper.eventPersonTreatmentTable(cases);
        return Tools.buildTableDataInfo(cases.getPageNum(), cases.getPageSize(), casesTables);
    }

    /**
     * 按负责人统计-及时分析表格用
     */
    @Override
    public TableDataInfo eventPersonAnalysisTable(EventDistributionTO eventDistributionTO) {
        List<Cases> casesList = getCasesVo(eventDistributionTO);
        return buildTimelyAnalysisTableDataInfoByPersonId(casesList, eventDistributionTO);
//        return Tools.buildTableDataInfo(cases.getPageNum(), cases.getPageSize(), casesTables);
    }

    /**
     * 按负责人统计-及时分析表格用
     */
    private List<Cases> getCasesVo(EventDistributionTO eventDistributionTO) {
        QueryWrapper<Cases> casesQueryWrapper = new QueryWrapper<>();
        if (Objects.isNull(eventDistributionTO.getStartDate())) {
            eventDistributionTO.setStartDate(DateUtil.parseDateTime(DateUtil.format(new Date(), DatePattern.NORM_MONTH_PATTERN) + "-01 00:00:00"));
        } else {
            eventDistributionTO.setStartDate(DateUtil.parseDateTime(DateUtil.formatDate(eventDistributionTO.getStartDate()) + " 00:00:00"));
        }
        if (Objects.isNull(eventDistributionTO.getEndDate())) {
            eventDistributionTO.setEndDate(DateUtil.parseDateTime(DateUtil.formatDate(new Date()) + " 23:59:59"));
        } else {
            eventDistributionTO.setEndDate(DateUtil.parseDateTime(DateUtil.formatDate(eventDistributionTO.getEndDate()) + " 23:59:59"));
        }
//        List<CasesTable> casesTables = casesMapper.eventPersonAnalysisTable(cases);
        List<Cases> casesList = getCaseList(eventDistributionTO, casesQueryWrapper);
        casesList.forEach(t -> {
            if (StringUtils.isEmpty(t.getPersonId())) {
                t.setPersonId("");
            }
        });
        return casesList;
    }

    @Override
    public List<List<Object>> eventPersonTreatment(Cases cases) {
        if (Objects.isNull(cases.getStartDate())) {
            cases.setStartDate(DateUtil.parseDateTime(DateUtil.format(new Date(), DatePattern.NORM_MONTH_PATTERN) + "-01 00:00:00"));
        } else {
            cases.setStartDate(DateUtil.parseDateTime(DateUtil.formatDate(cases.getStartDate()) + " 00:00:00"));
        }
        if (Objects.isNull(cases.getEndDate())) {
            cases.setEndDate(DateUtil.parseDateTime(DateUtil.formatDate(new Date()) + " 23:59:59"));
        } else {
            cases.setEndDate(DateUtil.parseDateTime(DateUtil.formatDate(cases.getEndDate()) + " 23:59:59"));
        }
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        List<String> dateList = null;
        if (cases.getDepid() != null && cases.getDepid() != "") {
            List<String> depIds = departService.getChildIdsByIId(cases.getDepid());
            cases.setDepIds(depIds);
        }
        if ("2".equals(cases.getDateType())) {
            dateList = Tools.getMonthList(format.format(cases.getStartDate()), format.format(cases.getEndDate()));
        } else {
            dateList = Tools.getBetweenDate(format.format(cases.getStartDate()), format.format(cases.getEndDate()));
        }
        List<CasesCharts2> list = casesMapper.eventPersonTreatment(cases);
        List<Object> res = new ArrayList<>();
        List<List<Object>> resList = new ArrayList<>();
        if (!list.isEmpty()) {
            Map<String, CasesCharts2> casesMap = GroupingByUtils.getGroupingForMapEntity(list, CasesCharts2::getCreateTime, Collectors.collectingAndThen(Collectors.toList(), value -> value.get(0)));
            for (String date : dateList) {
                res.add(date);
                if (casesMap.containsKey(date)) {
                    res.addAll(casesMap.get(date).getResList());
                } else {
                    res.add(0);
                    res.add(0);
                    res.add(0);
                    res.add(0);
                    res.add(0);
                    res.add(0);
                }
                resList.add(res);
                res = new ArrayList<>();
            }
        } else {
            for (String date : dateList) {
                res.add(date);
                res.add(0);
                res.add(0);
                res.add(0);
                res.add(0);
                res.add(0);
                res.add(0);
                resList.add(res);
                res = new ArrayList<>();
            }
        }
        return resList;
    }

    @Override
    public List<List<Object>> eventPersonAnalysis(EventDistributionTO eventDistributionTO) throws ParseException {
        QueryWrapper<Cases> casesQueryWrapper = new QueryWrapper<>();
        if (Objects.isNull(eventDistributionTO.getStartDate())) {
            eventDistributionTO.setStartDate(DateUtil.parseDateTime(DateUtil.format(new Date(), DatePattern.NORM_MONTH_PATTERN) + "-01 00:00:00"));
        } else {
            eventDistributionTO.setStartDate(DateUtil.parseDateTime(DateUtil.formatDate(eventDistributionTO.getStartDate()) + " 00:00:00"));
        }
        if (Objects.isNull(eventDistributionTO.getEndDate())) {
            eventDistributionTO.setEndDate(DateUtil.parseDateTime(DateUtil.formatDate(new Date()) + " 23:59:59"));
        } else {
            eventDistributionTO.setEndDate(DateUtil.parseDateTime(DateUtil.formatDate(eventDistributionTO.getEndDate()) + " 23:59:59"));
        }
        List<Cases> casesList = getCaseList(eventDistributionTO, casesQueryWrapper);
        fillDepId(casesList);
        return buildTimelyAnalysisResultList(casesList, eventDistributionTO);
    }

    /**
     * 处理情况列表(按责任机构统计)导出
     *
     * @param eventDistributionTO
     * @return java.util.List<java.util.List < java.lang.Object>>
     * @author zcy
     * @date 2021/10/15 13:52
     */
    @Override
    public List<TreatmentTableVO> getTreatmentTableExcel(EventDistributionTO eventDistributionTO) {
        QueryWrapper<Cases> casesQueryWrapper = new QueryWrapper<>();
        Integer[] integers = {1, 2, 3, 4, 5};
        casesQueryWrapper.lambda().in(Cases::getStatus, integers);
        if (CollectionUtils.isNotEmpty(eventDistributionTO.getDepNames())) {
            casesQueryWrapper.lambda().in(Cases::getDepName, eventDistributionTO.getDepNames());
            Boolean flag = false;
            for (String depName : eventDistributionTO.getDepNames()) {
                if (StringUtils.isEmpty(depName)) {
                    flag = true;
                    break;
                }
            }
            if (flag) {
                casesQueryWrapper.lambda().or().isNull(Cases::getDepName);
            }
        }
        List<Cases> casesList = getCaseList(eventDistributionTO, casesQueryWrapper);
        fillDepId(casesList);
        List<TreatmentTableVO> vo = getTreatmentTableVOList(casesList);
        return vo;
    }

    /**
     * 及时处理列表(按责任机构统计)导出
     *
     * @param eventDistributionTO
     * @return java.util.List<java.util.List < java.lang.Object>>
     * @author zcy
     * @date 2021/10/15 13:52
     */
    @Override
    public List<TimelyAnalysisTableVO> getTimelyAnalysisTableExcel(EventDistributionTO eventDistributionTO) {
        QueryWrapper<Cases> casesQueryWrapper = new QueryWrapper<>();
        Integer[] integers = {1, 2, 3, 4, 5};
        casesQueryWrapper.lambda().in(Cases::getStatus, integers);
        if (CollectionUtils.isNotEmpty(eventDistributionTO.getDepNames())) {
            casesQueryWrapper.lambda().in(Cases::getDepName, eventDistributionTO.getDepNames());
            Boolean flag = false;
            for (String depName : eventDistributionTO.getDepNames()) {
                if (StringUtils.isEmpty(depName)) {
                    flag = true;
                    break;
                }
            }
            if (flag) {
                casesQueryWrapper.lambda().or().isNull(Cases::getDepName);
            }
        }
        List<Cases> casesList = getCaseList(eventDistributionTO, casesQueryWrapper);
        fillDepId(casesList);
        List<TimelyAnalysisTableVO> vo = getTimelyAnalysisTableVOList(casesList);
        return vo;
    }

    @DataScope(deptAlias = "depid", userAlias = "create_uid,person_id,cc_uid")
    public List<Cases> casesTableListExcel(BaseEntity entity, JSONObject params) {

        String uid = LoginUtils.getUser().getUid();
        JSONObject json = new JSONObject();
        if (params == null) {
            params = new JSONObject();
        }
        QueryWrapper<Cases> queryWrapper = new QueryWrapper<>();
        String sortType = params.getString("sortType");
        String sortField = params.getString("sortField");
        if (entity.getParams().containsKey("dataScope")&&StringUtils.isNotEmpty(entity.getParams().get("dataScope"))) {
            queryWrapper.lambda().apply(entity.getParams().get("dataScope").toString());
        }
        if (StringUtils.isNotEmpty(sortField) && StringUtils.isNotEmpty(sortType) && "asc".equals(sortType)) {
            queryWrapper.lambda().orderByAsc(Cases::getCreateTime);
        } else {
            queryWrapper.lambda().orderByDesc(Cases::getCreateTime);
        }
        String caseId = params.getString("caseId");
        if (StringUtils.isNotEmpty(caseId)) {
            queryWrapper.lambda().eq(Cases::getCaseId, caseId);
        }
        String ids = params.getString("ids");
        if (StringUtils.isNotEmpty(ids)) {
            queryWrapper.lambda().in(Cases::getCaseId, Arrays.asList(ids.split(",")));
        }
        String personId = params.getString("personId");
        if (StringUtils.isNotEmpty(personId)) {
            queryWrapper.lambda().eq(Cases::getPersonId, personId);
        }
        Integer status = params.getInteger("status");
        if (StringUtils.isNotEmpty(status)) {
            queryWrapper.lambda().eq(Cases::getStatus, status);
        }
        String statuses = params.getString("statuses");
        if (StringUtils.isNotEmpty(statuses)) {
            queryWrapper.lambda().in(Cases::getStatus, statuses.split(","));
        }
        String depId = params.getString("depId");
        if (StringUtils.isNotEmpty(depId)) {
            queryWrapper.lambda().eq(Cases::getDepid, depId);
        }
        String caseIssueId = params.getString("caseIssueId");
        if (StringUtils.isNotEmpty(caseIssueId)) {
            queryWrapper.lambda().eq(Cases::getCaseIssueId, caseIssueId);
        }
        String caseIssueChildId = params.getString("caseIssueChildId");
        if (StringUtils.isNotEmpty(caseIssueChildId)) {
            queryWrapper.lambda().eq(Cases::getCaseIssueChildId, caseIssueChildId);
        }
        String caseNo = params.getString("caseNo");
        if (StringUtils.isNotEmpty(caseNo)) {
            queryWrapper.lambda().like(Cases::getCaseNo, caseNo);
        }
        String caseLevelId = params.getString("caseLevelId");
        if (StringUtils.isNotEmpty(caseLevelId)) {
            queryWrapper.lambda().eq(Cases::getCaseLevelId, caseLevelId);
        }
        String startDate = AttributeUtils.timeCompletion(params.getString("startDate"), 's');
        String endDate = AttributeUtils.timeCompletion(params.getString("endDate"), 'e');
        String date = params.getString("date");
        if (StringUtils.isNotEmpty(startDate) && StringUtils.isNotEmpty(endDate)) {
            queryWrapper.lambda().between(Cases::getCreateTime, startDate, endDate);
        } else if (StringUtils.isNotEmpty(date) && StringUtils.isNotEmpty(date)) {
            queryWrapper.lambda().between(Cases::getCreateTime, date + " 00:00:00.0", date + " 23:59:59.999");
        }
        String isPostpone = params.getString("isPostpone");
        if (StringUtils.isNotEmpty(isPostpone)) {
            queryWrapper.lambda().eq(Cases::getIsPostpone, isPostpone);
        }
        String isOverdue = params.getString("isOverdue");
        if (StringUtils.isNotEmpty(isOverdue)) {
            queryWrapper.lambda().eq(Cases::getIsOverdue, isOverdue);
        }
        String createUid = params.getString("createUid");
        if (StringUtils.isNotEmpty(createUid)) {
            queryWrapper.lambda().eq(Cases::getCreateUid, createUid);
        }
        return casesMapper.selectList(queryWrapper);
    }

    public List<CasesTable> eventPersonTreatmentTableExcel(Cases cases) {
        if (Objects.isNull(cases.getStartDate())) {
            cases.setStartDate(DateUtil.parseDateTime(DateUtil.format(new Date(), DatePattern.NORM_MONTH_PATTERN) + "-01 00:00:00"));
        } else {
            cases.setStartDate(DateUtil.parseDateTime(DateUtil.formatDate(cases.getStartDate()) + " 00:00:00"));
        }
        if (Objects.isNull(cases.getEndDate())) {
            cases.setEndDate(DateUtil.parseDateTime(DateUtil.formatDate(new Date()) + " 23:59:59"));
        } else {
            cases.setEndDate(DateUtil.parseDateTime(DateUtil.formatDate(cases.getEndDate()) + " 23:59:59"));
        }
        List<CasesTable> casesTables = casesMapper.eventPersonTreatmentTable(cases);
        return casesTables;
    }

    /**
     * 按负责人统计-及时分析表格导出用
     */
    @Override
    public List<TimelyAnalysisTableVO> eventPersonAnalysisTableExcel(EventDistributionTO eventDistributionTO) {
        List<Cases> casesList = getCasesVo(eventDistributionTO);
        return getTimelyAnalysisTableVOS(casesList);
    }

    @Override
    public List<CasesTable> eventPersonByCreaterExcel(Cases cases) {
        List<CasesTable> casesTables = getCasesTablesList(cases);
        return casesTables;
    }

    /**
     * 按负责人统计-问题类型统计表格导出
     *
     * @param cases
     * @return
     */
    @Override
    public List<CasesTable> eventPersonByProblemExcel(Cases cases) {
        List<CasesTable> casesTables = getCasesTablesVO(cases);
        return casesTables;
    }
}
